I have a Server
and two clients
.
I have finished i/o with the client A
and client B
.
Now i need to reconnect to Client A
and do some input/output with that client.
I store connectedClientsHistory
in a list of String with their ip
and ports
.
But the problem is that i got Exception java.net.ConnectException: Connection refused: connect
Here is my code:
public class Server extends Thread {
private static int serverPort = 9090;
private static ServerSocket listener;
private static int numberOfConnectedClients;
private static int numberOfPlayers;
List<String> orderOfConnectedClients = new LinkedList<String>();
public Server(int port) throws IOException {
listener = new ServerSocket(port);
this.serverPort = port;
}
public static void main(String[] args) throws IOException {
Thread thread = new Server(9090);
thread.start();
}
public void run() {
while (numberOfConnectedClients < numberOfPlayers) {
try {
System.out.println("Waiting for clients on server Port " + listener.getLocalPort() + " ...\n");
Socket connectedClient = listener.accept();
numberOfConnectedClients++;
System.out.println("Connected Client ip/port: " + connectedClient.getRemoteSocketAddress().toString());
orderOfConnectedClients.add(connectedClient.getRemoteSocketAddress().toString());
System.out.println("History Connected Clients: " + orderOfConnectedClients);
DataOutputStream outToClient = new DataOutputStream(connectedClient.getOutputStream());
InputStream inFromClient = connectedClient.getInputStream();
DataInputStream in = new DataInputStream(inFromClient);
if (numberOfConnectedClients == numberOfPlayers) {
// notify to the first client
String[] firstClient = orderOfConnectedClients.get(0).split(":");
System.out.println(firstClient);
Socket reconnectSocket = new Socket(firstIp, firstPort);
DataOutputStream outToClient2 = new DataOutputStream(reconnectSocket.getOutputStream());
outToClient2.writeUTF("Reconnect?");
// how access to the first client?
}
} catch (Exception e) {
e.printStackTrace();
}
}
}