Java uses NiO package to realize socket communication instance code

Previous articles introduced using Java IO and Java Net class library. The following describes the use of Java Socket implemented by NiO class library.

java. NiO package is added after Java 1.4 to improve the efficiency of I / O operations. NiO package mainly includes the following classes or interfaces:

NiO package mainly improves I / O operation efficiency through the following two aspects:

Let's take a look at how to implement socket functions through these class libraries in the program.

First, let's introduce some auxiliary classes

The auxiliary class serializableutil is used to serialize Java objects into byte arrays or deserialize byte arrays into Java objects.

The auxiliary classes myrequestobject and myresponseobject are ordinary Java objects that implement the serializable interface. Myrequestobject class is the request sent by the client, and myresponseobject is the response made by the server.

Let's take a look at the server-side code. Some English comments are very helpful for understanding the code. The comments are mainly documents and examples from the JDK, which will not be translated here

The following is the client code. The code is relatively simple. It starts 100 threads to access the server

Finally, test the above code. First run the server class, and then run the client class. You can see the sent or received myrequestobject or myresponseobject objects on the server and client consoles respectively.

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>