The preparation of TCP protocol network program, the key lies in the skilled use of ServerSocket socket, TCP communication in all information transmission is based on the input and output stream of ServerSocket class.

directory

TCP Concepts

ServerSocket class

Server-side program

Client program


Hello! Hello everyone! I’m grey Ape!

In my last blog, I shared the basic knowledge of network programming, including IP, TCP, UDP, ports and sockets. If you want to know more, you can read my article “The basic knowledge of network programming must know”. So today big bad Wolf will share with you how to use TCP/IP network program development.

 

TCP Concepts

First, understand the basic concepts of TCP.

We know that TCP is a reliable rather than secure network protocol. It ensures that data is delivered exactly as it is sent from one end to the other, and that the order of arrival is the same as the order of departure. Therefore, during TCP communication, ensure that the connection between the client and server is smooth.

The preparation of TCP protocol program, still rely on the Socket class to achieve, and the use of TCP protocol communication between the two programs are primary and secondary points, that is, a server program, another is the client program. So the two are also slightly different in functionality and writing. The diagram below shows the communication between the server and the client:

 

The above is the schematic diagram of the connection between the client and the server in TCP. In which the key role is the ServerSocket and the client Socket Socket. Through these two sockets to establish the server and client, so as to use the functions in the data communication.

The ServerSocket class has a lot to be aware of, so the big bad Wolf will share the ServerSocket class with you:

 

ServerSocket class

The ServerSocket class exists in the Java.net package and represents the socket on the server side. It needs to be imported before use. We also know that the main function of the ServerSocket class is to wait for the request from the client on the network and connect through the specified port.

It is worth noting: Server socket only once with a client socket connection, so if there is more than one client at the same time send a connection request, the server socket will request the client to deposit into the queue, and then take out a socket connection with the server to establish a socket, but the server can accommodate the client socket is not infinite, When the number of connections requested is greater than the maximum capacity, the additional requests will be rejected. Generally, the default queue size is 50.

The constructor of the ServerSocket class usually throws IOException in the following forms:

  • ServerSocket() : creates an unbound ServerSocket
  • ServerSocket(inr port) : creates a ServerSocket bound to a specific port
  • ServerSocket(int Port, int Backlog) : Create server sockets from the specified backlog and bind them to the specified server port,
  • ServerSocket(int Port, int Backlog, InetAddress bindAddress) : Create a server using the specified port, listen for the backlog and the IP address to be bound locally. In this case, the computer has multiple network adapters and IP addresses. Users can specify which network adapter or IP address the ServerSocket waits for connection requests from users.

Here are some common methods in the ServerSocket class:

methods The return value instructions
accept() Socket Wait for the client to connect, and if so, create a client socket
isBound() boolean Check the binding status of the ServerSocket
getInetAddress() InetAddress Returns the local address of this server socket
isClosed() boolean Returns the closed state of the server socket
close() void Close the server socket
bind(SocketAddress endpoint) void Bind the ServerSocket to a specific address (IP address and port number)
getInetAddress() int Returns the port number on which the server socket is waiting

Now that you know the basic methods of the ServerSocket class, it’s time to connect the client to the server.

On the server side, we can call the AccPET () method of the ServerSocket class to establish a connection with the client. In this case, a Socket object connected to the client is returned. Use the getInetAddress() method to get the IP address of the requesting client.

The Socket object on the server side uses the getOutputStream() method to get the output stream. Gets the input stream from the Socket object pointing to the client using the getInputStream() method. In the same way that the Socket object on the client gets an output stream using getOutputStream(), it points to the Socket object on the server that gets an input stream using getInputStream(). Thus realize the process of sending data to the server by the client.

Note: The accPET () method blocks the thread from continuing execution. If no client call is received on the corresponding interface, the program will stay there until the client call is received. However, if the server does not receive a call request from the client and the accpet() method is not blocked, ServerSocket is not bound to the server because the port number used by another program is not bound to the server. In this case, try changing the port number.

 

Understand the TCP protocol communication process, the next is to write TCP communication procedures!

In network communication, if the client is only required to send information to the server, does not require the server to the client feedback information referred to as the “one-way communication”, ask the client and server communicate with each other on both sides of the process is called “two-way communication”, two-way communication is much more than a one-way communication only a server to the client the process of sending a message,

Next is the preparation of server-side and client-side programs respectively:

 

Server-side program

package server_1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;


public class MyTcp {

	private ServerSocket server;	// Set the server socket
	private Socket client;		// Set the client socket
	
	// Connect to the client function
	void getServer(a)
	{
		try {
			server = new ServerSocket(1100);	// Set the server port to 1100
			System.out.println("Server set up successfully! Waiting for connection......");
			client = server.accept();	// Call the server function to connect to the client
			System.out.println("Client connection successful! IP is:" + client.getInetAddress());	// Return the client IP address
			getClientMessage();		// Call the message transfer and receive functions
			
		} catch (IOException e) {
			// TODO Auto-generated catch blocke.printStackTrace(); }}void getClientMessage(a)
	{
		try {
			while (true) {
				InputStream is = client.getInputStream();	// Get the input stream from the client
				byte[] b = new byte[1024];	// Define a byte array
				int len = is.read(b);	// Since information is transmitted in binary form, data is read in binary form
				String data = new String(b, 0,len);
				System.out.println("Message from client:" + data);
				
				// Define the output stream to be sent to the client
				OutputStream put = client.getOutputStream();
				String putText = "I've received it! Welcome!";
				put.write(putText.getBytes());	// Write output stream information in binary form}}catch (Exception e) {
			// TODO: handle exception
		}
		try {
			// If the client byte stream is not empty, close the client
			if(server ! =null) { server.close(); }}catch (Exception e) {
			// TODO: handle exception}}public static void main(String[] args) {
		// TODO Auto-generated method stub
		MyTcp myTcp = new MyTcp();	// Call the class to generate an object
		myTcp.getServer();	// Call the method}}Copy the code

 

Client program

package client_1;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class MyClient {
	private Socket client;	// Define the client socket
	
	// Create the client function
	void getClient(a)
	{
		try {
			client = new Socket("127.0.0.1".1100);	// Set up the client using IP address 127.0.0.1 and port 1100, the same as the server
			System.out.println("Client established successfully!");
			
			setClientMessage();		// Call the client message writing function
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch blocke.printStackTrace(); }}// Define the client message writing function
	void setClientMessage(a)
	{
		try {		
			OutputStream pt = client.getOutputStream();		// Set up the client information output stream
			String printText = "Hello server! I'm the client!";	
			pt.write(printText.getBytes());		// Output the information in binary form
			
			InputStream input = client.getInputStream();	// Set up the client information input stream
			byte [] b = new byte[1024];		// Define a byte array
			int len = input.read(b);	// Read the received binary information stream
			String data = new String(b, 0,len);
			System.out.println("Received server message:" + data);
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			// If the client information flow is not empty, the client has established a connection and shut down the client
			if(client ! =null) { client.close(); }}catch (Exception e) {
			// TODO: handle exception}}public static void main(String[] args) {
		// TODO Auto-generated method stub
		// Generate a client class object
		MyClient myClient  = newMyClient(); myClient.getClient(); }}Copy the code

Note at the same time: after the client and server are successfully set up, you should open the server and wait for connection, and then open the client for connection. Similarly, when closing the client, you should close the client first, and then close the server.

 

Take the above program as an example:

Open the server and wait for the client to connect

The connection between the client and the server is successful, and two-way communication is realized:

Note: When multiple network applications are installed on a machine, it is very likely that the specified port has been occupied, or even that the previously fine application suddenly freezes. In this case, the port is occupied by another application. In this case, you can run netstat-help to help. You can use the command netstat-an to view the ports used by the program.

 

Think useful remember to like attention yo!

At the same time, you can also follow my wechat public account “Gray Wolf Hole master” background reply “Java notes” to get Java intensive video, interview treasure book, project case analysis, project architecture and other information sharing!

The Wolf is looking forward to making progress with you