This is the first day of my participation in the Gwen Challenge in November. Check out the details: the last Gwen Challenge in 2021

An overview

TCP/UDP protocol promotes the extensive application of client/server communication mode. In the two processes that communicate, one is the client process and the other is the server process. A client process makes a request to a server process for a service, and the server process responds to the request. Java network program based on TCP/IP protocol, is committed to the application layer, the transmission layer to the application layer provides a Socket Socket interface, Socket encapsulates the lower data transmission details, the application layer program through Socket to establish a connection with the remote host, as well as data transmission.

From the perspective of the application layer, the communication process between two processes starts from establishing a TCP connection. After the connection is successful, data can be exchanged. Finally, the connection is disconnected and the service ends. A socket can be regarded as a transmitter at both ends of communication. Processes send and receive data through the socket.

The following simple client/server program is based on ServerSocket and Socket to write server and client programs.

Creating the Server side

The server program receives connection requests from the client program by always listening on the port, so in the server program, you need to create a ServerSocket object and pass in the specified listening port during initialization.

ServerSocket serverSocket = new ServerSocket(40000);
Copy the code

The ServerSocket constructor is responsible for registering the current process as a server process in the operating system. The server program then calls the Accept () method of the ServerSocket object, which listens on the port waiting for a connection request from the client. If a connection request is received, the Accept () method returns a Socket object. The Socket object forms a communication line with the Socket object of the client.

socket = serverSocket.accept();// Wait for the client to connect
Copy the code

** The Socket class provides the getInputStream() and getOutputStream() methods, which return an InputStream and an OutputStream, respectively. ** programs can send data to each other simply by writing data to the output stream. Simply read data from the input stream and receive data from the other side.

Like normal I/O streams, input and output streams of sockets can be decorated with filter streams. In the following code, take the output stream and decorate it with PrintWriter, whose println() method writes a line of data; The following code then takes the input stream and decorates it with BufferedReader, whose readLine() method reads a line of data:

/ / the output stream
OutputStream socketoutput = socket.getOutputStream();
PrintWriter printWriter = new PrintWriter(socketoutput,true);

/ / input stream
InputStream socketinput = socket.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socketinput));
Copy the code

The server.accept () method returns a Socket object, indicating that a connection has been established with a client. Next we get the output and input streams from the Socket object and decorate them with PrintWriter and BufferedReader, respectively. And then I keep calling the BufferedReader’s readLine() method to read the string that the client sent me, and THEN I’m calling PrintWriter’s println() method to return the string to the client and the server gets the string.

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class ServerDemo {
    private int port = 40000;
    private ServerSocket serverSocket;
    
    public ServerDemo(a) throws IOException {
        serverSocket = new ServerSocket(port);
        System.out.println("Server started");
    }

    public PrintWriter getWriter(Socket socket) throws IOException {
        OutputStream socketoutput = socket.getOutputStream();
        PrintWriter printWriter = new PrintWriter(socketoutput,true);
        return printWriter;
    }

    public BufferedReader getReader(Socket socket) throws IOException {
        InputStream socketinput = socket.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socketinput));

        return bufferedReader;
    }
    public void server(a)
    {
        while(true)
        {
            Socket socket = null;
            try {
                socket = serverSocket.accept();// Wait for the client to connect
                System.out.println("Client connected, address:"+socket.getInetAddress()+"Port number:"+socket.getPort());

                PrintWriter writer = this.getWriter(socket);
                BufferedReader reader = this.getReader(socket);
                String msg = null;
                while((msg = reader.readLine())! =null)
                {
                    System.out.println(socket.getInetAddress()+""+socket.getPort()+"Message sent:"+msg);
                    writer.println("Server received:"+ msg); }}catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    if(socket! =null)
                        socket.close();
                } catch(IOException e) { e.printStackTrace(); }}}}public static void main(String[] args) throws IOException {
        newServerDemo().server(); }}Copy the code

Creating a Client

In the client program, in order to communicate with the server-side process, we first need to create a Socket object:

String host = "localhost";// IP address of the server
int port = 40000;
Socket socket = new Socket(host,port);;
Copy the code

In the above Socket constructor, the host parameter indicates the name of the host where the Server process resides, and the port parameter indicates the port on which the Server process listens. If host is set to localhost, the Client and Server processes run on the same host. If the Socket object is successfully created, the connection between the Client and Server is established. The Client then receives the output stream and input stream from the Socket object and can exchange data with The EchoServer.

The following is the client program, the main function is the talk function, which continuously reads the string input by the client, and then outputs the string to the Server, and then prints the information returned by the Server. When the user enters “”, the client is closed.

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class ClientDemo {
    private String host = "localhost";
    private int port = 40000;
    private Socket socket;

    public ClientDemo(a) throws IOException {
        socket = new Socket(host,port);
        System.out.println("Start client");
    }

    public PrintWriter getWriter(Socket socket) throws IOException {
        OutputStream socketoutput = socket.getOutputStream();
        PrintWriter printWriter = new PrintWriter(socketoutput,true);
        return printWriter;
    }

    public BufferedReader getReader(Socket socket) throws IOException {
        InputStream socketinput = socket.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socketinput));

        return bufferedReader;
    }

    public void talk(a) throws IOException {
        try {
            BufferedReader reader = this.getReader(socket);
            PrintWriter wirter = this.getWriter(socket);

            String msg = null;
            Scanner in = new Scanner(System.in);
            while(! (msg = in.nextLine()).equals(""))
            {
                wirter.println(msg);
                System.out.println("1234"); System.out.println(reader.readLine()); }}catch (IOException e) {
            e.printStackTrace();
        }finally{ socket.close(); }}public static void main(String[] args) throws IOException {
        newClientDemo().talk(); }}Copy the code

The results show