I have a server which is supposed to open a ServerSocket
connection to every client. The problem is, I need the clients to check if the ConnectionPort is in use already.
That means the Clients should check port 12345 and get a result if there is a ServerSocket
"waiting" or not, and if not they take the next etc.
So in the end two or three clients are connected to the Server on port 12345, 12346, 12347...
I wrote this:
serverSocket = new ServerSocket(incomingPort, 1); // backlog 1 = Minimum
incomingSocket = serverSocket.accept();
readerIn = new BufferedReader(new InputStreamReader(incomingSocket.getInputStream()));
outgoingSocket = new Socket(incomingSocket.getInetAddress().getHostAddress(), outgoingPort);
dataOutputStream = new BufferedOutputStream(outgoingSocket.getOutputStream());
pwOut = new OutputStreamWriter(outgoingSocket.getOutputStream());
I get the first client connected and open (in the last three lines) another connection "back" to the client. On the client side I wrote almost the same, the other way around:
outgoingSocket = new Socket(serverIP, inPort1);
dataOutputStream = new BufferedOutputStream(outgoingSocket.getOutputStream());
pwOut = new OutputStreamWriter(outgoingSocket.getOutputStream());
serverSocket = new ServerSocket(outPort1);
incomingSocket = serverSocket.accept();
readerIn = new BufferedReader(new InputStreamReader(incomingSocket.getInputStream()));
The next client that tries to open a connection is doing the same, starting with the same port. I was hoping to get an Exception
like a ConnectException
or so, but nothing. I guess it is related to the backlog "buffer". It continues with everything and waits to become a ServerSocket
but it waits forever. The server itself is already occupied with the first connection.
I read many posts but they all say that outgoingSocket.isConnected()
is giving true
and .isClosed()
is giving false
, at least until the timeout. Is there any way of determing that the server is already occupied? Or at least to "disable" the backlog so all incoming connections are refused?
I am not sure if you understand concept of client-server communication and socket interface. You don't need to create a new socket to communicate from server to client, TCP connections are bidirectional and you can write to the same socket that you read from.
Please refer to the official documentation for the good EXAMPLE of client-server, or follow the full TUTORIAL.
If you still want to proceed with your approach, where the server accepts only a single connection, you need to close serverSocket
in server after accepting the connection. Communication will still be possible using your incomingSocket
class.