Java implementation of socket client connection server

This example is only a simple function demonstration, and the code is not rigorous. It just explains how the client connects to the server.

The code is tested, compiled and run under the integrated eclipse tool, as shown in the following figure:

Client echoclient Java code:

Server echoserver Java code:

The results of my direct debugging under the eclipse tool are as follows:

Let's take another look at an example of helloword level java socket communication. Communication process:

Start the server side first and enter an endless loop to always listen for connection requests on a port. Then run the client side. The client sends a connection request. After listening to the request, the server sends back an acceptance message to the client, establishes the connection, starts a thread to process the request, and then continues to listen to other requests in an endless loop. After the client enters the string, press enter to send data to the server. After reading the data, the server replies to the client data. After this request is processed, the started thread dies. If the client receives the return data other than "OK", it will send the connection request and send the data again, and the server will start a thread again for this connection to respond... Until the return data received by the client is "OK", the client exits.

Server source code:

Client source code:

Note: when the socket output stream writes data in writeutf, the input stream reads relevant data in readutf. Otherwise, eofexception exception will be thrown.

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
分享
二维码
< <上一篇
下一篇>>