Hi I have a GUI application that is working fine. I created a socket server. When I create a new object of the Server class in program the GUI application stops responding.
This is my server class. If I do
Server s = new Server();
in my main application it stops working. How should I add it? Making a new thread? I tried
Thread t = new Thread(new Server());
t.start();
but the problem persisted. Please, I'll appreciate your help.
package proj4;
import java.net.*;
import java.io.*;
public class Server implements Runnable {
ServerSocket serverSocket = null;
Socket clientSocket = null;
ObjectOutputStream out = null;
ObjectInputStream in = null;
int port;
static int defaultPort = 30000;
boolean isConnected = false;
Thread thread;
DataPacket packet = null;
public Server(int _port) {
try {
serverSocket = new ServerSocket(_port);
serverSocket.setSoTimeout(1000*120); //2 minutes time out
isConnected = true;
System.out.println("server started successfully");
thread = new Thread(this);
thread.setDaemon(true);
//thread.run();
} catch (IOException e) {
System.err.print("Could not listen on port: " + port);
System.exit(1);
}
try {
System.out.println("Waiting for Client");
clientSocket = serverSocket.accept();
System.out.println("Client Connected");
thread.run();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
try {
out = new ObjectOutputStream(clientSocket.getOutputStream());
System.out.println("output stream created successfully");
} catch (IOException e) {
e.printStackTrace();
}
try {
in = new ObjectInputStream(clientSocket.getInputStream());
System.out.println("input stream created successfully");
} catch (IOException e) {
e.printStackTrace();
}
}
public Server() {
this(defaultPort); //server listens to port 30000 as default
}
public void run() {
System.out.println("Thread running, listening for clients");//debugging purposes
while (isConnected) {
try {
packet = this.getData();
Thread.sleep(0);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
public DataPacket getData() {
try {
packet = (DataPacket)in.readObject();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
return packet;
}
public void sendData(DataPacket dp) {
try {
out.writeObject(dp);
} catch (IOException e) {
e.printStackTrace();
}
try {
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public void closeConnection() throws IOException {
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}