Simple socket communication instance based on TCP protocol (Java)

I haven't written a blog for a long time. I was busy working on the project some time ago and lost some time. I continue to write today~

Today, let's talk about the simple application of socket communication, what is socket and the basis of some network programming. We won't mention it here, but only record the simplest, understandable and practical things.

1. First, let's look at the communication model between socket server and client based on TCP protocol:

Socket communication steps: (4 steps)

1. Establish server socket and client socket

2. Open the output / input stream connected to the socket

3. Read and write according to the protocol

4. Close the corresponding resources

2. Associated API:

1. First, let's look at ServerSocket

Class ServerSocket

This class implements server sockets. The server socket waits for a request to pass through the network. It performs certain operations based on the request and may then return results to the requester.

The actual work of the server socket is performed by an instance of the socketimpl class. An application can configure itself by changing the socket factory that creates the socket implementation to create a socket suitable for the local firewall.

Some important methods: (see the official API for details)

ServerSocket (int port, int backlog) creates a server socket using the specified backlog and binds it to the specified local port number.

Bind (socketaddress endpoint, int backlog) binds the ServerSocket to a specific address (IP address and port number).

Socket (InetAddress, int port) creates a stream socket and connects it to the specified port number of the specified IP address.

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