Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Socket still first choice for TCP/IP programming in Java?

Tags:

java

tcp

sockets

I need to interact with a server over TCP/IP with a basic message/response protocol (so for each request I shall receive a defined response).

In the JVM ecosystem, I think Java Socket was the tool to use 15 years ago, but I'm wondering if there is anything more suitable nowadays in the JDK? For example, with Java Sockets one still needs to manually timeout a request if no answer is received, which feels really old fashioned.

So is there anything new in the JDK or JVM universe?

like image 724
Sebi Avatar asked Feb 16 '16 11:02

Sebi


1 Answers

No, there are much better option nowadays which allow you to implement your client/server asynchronously without additional threading.

Look at SocketChannel from nio or even better AsynchronousSocketChannel from nio2. Check this tutorial

Especially the latter option will allow you to just start the connection listener and register callback which will be called whenever new connection is requested, data arrived, data was written etc.

Also consider looking at some high level solutions like Netty. It will take care of the network core, distribute load evenly to executors. Additionally it provides clears separation of the network layer and processing layer. For the processing layer it will provide you with lot of reusable codecs for common protocols.

like image 71
Zbynek Vyskovsky - kvr000 Avatar answered Nov 11 '22 16:11

Zbynek Vyskovsky - kvr000