package de.luk45.connect;
import java.io.IOException;
import de.luk45.gui.MainPanel;
import socketio.Socket;
public class Client {
private Socket socket;
private boolean running = false;
private Client() {
}
private static Client instance;
public static Client getInstance() {
if (instance == null) {
instance = new Client();
}
return instance;
}
public boolean connect(String server, int port) {
socket = new Socket(server, port);
MainPanel.outLn("Connecting to " + server + ":" + port);
if (!socket.connect()) {
socket = null;
MainPanel.outLn("connect failed");
return false;
} else {
MainPanel.outLn("connected");
running = true;
MainPanel.outLn("starting listening Thread");
new Thread() {
public void run() {
while (running) {
try {
String s = socket.readLine();
if (s != null)
MainPanel.outLn(s);
//else
// //running = false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//MainPanel.outLn("server disconnected. You should disconnect too.");
}
}.start();
}
return true;
}
public boolean disconnect() {
if (socket != null) {
try {
MainPanel.outLn("closing connection");
running = false;
socket.close();
socket = null;
return true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
MainPanel.outLn("no connection open");
return false;
}
public boolean writeLine(String text) {
if (socket != null) {
try {
MainPanel.outLn("writing: " + text);
socket.write(text + "\n");
return true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
MainPanel.outLn("no connection open");
return false;
}
public String readLine() {
if (socket != null) {
try {
return socket.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
}