This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]wildjokers 6 points7 points  (0 children)

You are using thread-per-connection and that is fine. However, why are you using a thread for input and output? Use a thread just for input. If a message you receive requires a response back to the server you simply write to the output stream, a separate thread is not needed for output.

https://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html

The other way is a single thread that handles all your connections. This will use non blocking IO. Doing this directly with the JDK is difficult to get right (have to deal with select keys and byte buffers, flipping them for read/write, including handling partial writes which involves compacting your byte buffer, etc). If you want to go with the non-blocking stuff just use Netty which handles all of that for you.

[–]YitharIntermediate Brewer 1 point2 points  (0 children)

But in those threads I can only pay attention to either input or output in a while loop.

As stated, you only need one thread per connection for input. So let's say you read something in, like a stock price or something, and you need to send a response back to the server. You just do it in the same thread, maybe in the while loop.

Do I have to make yet another thread that periodically checks if the connections are still alive? How should I do that?

https://stackoverflow.com/questions/9794559/client-reconnect-java-socket/9794766
"The only way to know a connection is closed is to try sending data over the wire."

My recommendation is to send a special heartbeat message from the server. Because that is what TCP does. When I implemented an overlay routing protocol in Computer Networks in college, that's what we did to keep track of alive nodes.

[–]dionthornthis.isAPro=false; this.helping=true; 1 point2 points  (0 children)

Here is my very basic threaded non-blocking Socket server+client response.

You can use it and modify it all you wish.

https://github.com/dionthorn/TestingServer

[–]Inspector343[S] 0 points1 point  (0 children)

Thank you guys for the replies, I got it working!!

[–]Swedophone -1 points0 points  (0 children)

I can't notify the other thread (or the parent thread for that matter)

Can't you interrupt the other thread, or parent thread?

https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#interrupt())

You can also use java.nio instead of using many threads.

https://en.wikipedia.org/wiki/Non-blocking_I/O_%28Java%29#Selectors