Skip to content
Advertisement

Java socket client/server

Hi i am trying to get some data about a socket client connecting to a mutltythreaded server process in the same machine. The server thread is triggered correctly and the client ip is retreived ok, but i cant seem to be able to send a string through the connection. THE CLIENT

THE SERVER THREAD

The line sent through is empty. CONNECTION ESTABLISHED

Advertisement

Answer

I looks like you’ve got a bit of a timing issue. The following is your code with correct timing. Note that I removed code unnecessary to the issue at hand.

Client: It looks like in the client, you were writing to the socket and immediately terminating the application (causing the connection to close). The doComms class was writing back to the client so I’ve added code to read the response. If, however, you were not expecting a response, you would still want to read in a byte. This will allow you to make sure you got the EOF rather than some data, and it blocks the current thread and keeps the connection alive.

Server: I’ve changed the server to allow a maximum number of connections at any given time rather than shutting down after the maximum number of connections has been established. Also, note that I the threads are not daemons. If you want to serve X number clients then shutdown, you need a mechanism to allow the threads to continue executing before shutting down ServerSocket

doComms: Not much has changed with this class… I just cleaned it up a bit and removed unnecessary lines of code.

Hope this helps 🙂

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement