Sto scrivendo un piccolo server TCP per la mia rete di casa, ma stò avendo qualche problemino con i Thread
package server;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPMainServer implements Runnable {
private final String serverName;
private final int port;
private final int MAX_CONNECTIONS;
ServerSocket serverSocket;
public TCPMainServer(String ServerName, int Port, int MAX_CONNECTIONS) {
this.serverName = ServerName;
this.port = Port;
this.MAX_CONNECTIONS = MAX_CONNECTIONS;
try (
ServerSocket s = new ServerSocket(port);) {
this.serverSocket = s;
} catch (IOException e) {
System.out.println("[TCPMainServer]" + serverName + " : can't create a socket to port " + port);
System.out.println("[TCPMainServer]" + serverName + e.getMessage());
System.exit(1);
} catch (IllegalArgumentException e) {
System.out.println("[TCPMainServer]" + serverName + " port number out of range");
System.out.println("[TCPMainServer]" + serverName + e.getMessage());
System.exit(2);
}
Thread t = new Thread(this, serverName);
t.setPriority(8);
t.start();
}
@Override
public void run() {
System.out.println("TCPMainServer");
/*try {
serverSocket = new ServerSocket(port);//////////////////////////////////////////////////
} catch (IOException ex) {
Logger.getLogger(TCPMainServer.class.getName()).log(Level.SEVERE, null, ex);
}*/
if (serverSocket.isBound() && !serverSocket.isClosed()) {
while (true) {
try (
Socket clientSocket = serverSocket.accept();) {
System.out.println("Connecting to a client");
TCPServer clientServer = new TCPServer(clientSocket);
Thread ThreadSrv = new Thread(clientServer, clientSocket.getInetAddress().toString());
ThreadSrv.setPriority(5);
ThreadSrv.start();
} catch (IOException e) {
System.out.println(this.serverName+"Exception caught when trying to listen on port " + port + " or listening for a connection");
System.out.println(this.serverName+e.getMessage());
} catch (TCPServer_BadSocketException ex) {
System.out.println(this.serverName+"Socket invalid");
}
}
} else {
System.out.println(this.serverName+"Error when accepting connections on " + serverSocket.toString());
}
}
}
Sapete dirmi perchè se posiziono la riga
ServerSocket s = new ServerSocket(port);
nel metodo run() ( quella commentata ) non ho problemi mentre se la metto nel costruttore ( come adesso ) il metodo run() mi dice
192.168.1.125Error when accepting connections on ServerSocket[addr=0.0.0.0/0.0.0.0,localport=1000]
nel momento in cui mi connetto con il client ???
Ps: programmo in c, conosco le basi del java