Socket programming - TCP mode

catalogue

summary

Socket communication based on TCP

Construction works

code

SocketServerTCP class

SocketThreadTCP

SocketClientTCP

demonstration

summary

Friends of Java development are not too unfamiliar with socket. We generally come into contact with it when we study Java courses. Socket is the intermediate software abstraction layer for the communication between the application layer and the TCP/IP protocol family. Especially in Java development, JDK has provided the interface required for Sokcet coding, which makes it easier for us to use socket to realize our network communication function.

As a recent project just needs socket, I'll review it here. Socket communication based on TCP and UDP is realized respectively.

Socket communication based on TCP

Socket communication includes Server and Client respectively.

Construction works

We first built a Java project to facilitate subsequent expansion. We still adopted the Maven method.

Give Project a name and storage path:

code

Get a Package to distinguish:

SocketServerTCP class

The Server of the Socket, mainly

Because we use multithreading to process the data sent by the client, we need to add a multithreading handler SocketThreadTCP later.

package com.ispeasant.socket.tcp;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServerTCP {
    public static void main(String[] args) {
        try {
            // Create the server through the ServerSocket class. The port is 8888 (different classes are used for TCP and UDP)
            ServerSocket serverSocket = new ServerSocket(8888);

            System.out.println("The server was started successfully");

            // Create a Socket object, which can be understood as a client
            Socket socket = new Socket();

            // Normally, we start the Server first and then the Client to connect to the Server
            // Therefore, we need to listen to the connection of the Client all the time
            while (true) {
                // Connect Client
                socket = serverSocket.accept();

                // We use multithreading, so we can connect multiple clients at the same time
                SocketThreadTCP socketThreadTCP = new SocketThreadTCP(socket);
                socketThreadTCP.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

SocketThreadTCP

package com.ispeasant.socket.tcp;

import java.io.*;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SocketThreadTCP extends Thread {
    // Create a Socket object
    private Socket socket = null;

    // A build function is defined through the Socket object and the server as the entry
    public SocketThreadTCP(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        // Get the data from the client
        InputStream clientIS = null;
        InputStreamReader clientISR = null;
        BufferedReader clentBR = null;

        // Send information to clients
        OutputStream serverOS = null;
        PrintWriter serverPW = null;

        try {
            clientIS = socket.getInputStream();
            clientISR = new InputStreamReader(clientIS);
            clentBR = new BufferedReader(clientISR);

            // Information sent by the client
            String clientInfo = null;

            while ((clientInfo = clentBR.readLine()) != null) {
                System.out.println(clientInfo);
            }
            // Turn off the socket input
            socket.shutdownInput();

            // At the same time, we can also send some information to the client to confirm that we have received the information from the client
            serverOS = socket.getOutputStream();
            serverPW = new PrintWriter(serverOS);

            // Add a timestamp to better distinguish
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
            Date date = new Date(System.currentTimeMillis());

            serverPW.write(date + ": Hello! I am the server and have received your message");
            serverPW.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // close resource
            if (serverPW != null) {
                serverPW.close();
            }

            if (serverOS != null) {
                try {
                    if (serverOS != null) {
                        serverOS.close();
                    }
                    if (clentBR != null) {
                        clentBR.close();
                    }
                    if (clientISR != null) {
                        clientISR.close();
                    }
                    if (socket != null) {
                        socket.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }


    }
}

SocketClientTCP

The Socket client can be used to communicate with the Server.

package com.ispeasant.socket.tcp;

import java.io.*;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SocketClientTCP {
    public static void main(String[] args) {
        try {
            // Create a socket object and specify the Server (ip and port of the Server)
            Socket socket = new Socket("localhost", 8888);

            // Send information to Server
            OutputStream clientOS = socket.getOutputStream();
            PrintWriter clientPW = new PrintWriter(clientOS);

            // Add a timestamp
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
            Date date = new Date(System.currentTimeMillis());

            clientPW.write(date + ": Hello, this is the client.");
            clientPW.flush();

            // Turn off socket output
            socket.shutdownOutput();

            // Receive Server information
            InputStream serverIS = socket.getInputStream();
            InputStreamReader serverISR = new InputStreamReader(serverIS);
            BufferedReader serverBR = new BufferedReader(serverISR);

            // Server information
            String serverInfo = null;

            while ((serverInfo = serverBR.readLine()) != null) {
                System.out.println(serverInfo);
            }

            // Close flow
            serverBR.close();
            serverISR.close();
            serverIS.close();
            clientPW.close();
            clientOS.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

demonstration

Start SocketServerTCP class first:

Because I use the IDEA development tool, I can start multiple programs at the same time, and then we start the SocketClientTCP class.

It can be seen here that the client has received the information from the server. Let's look at the server again.

Therefore, it can also be seen that the server also received the information sent by the client. It is proved that the Socket TCP communication has been successful.

If you still want to continue testing, don't shut down the server program and start the client program again.

Keywords: Java socket tcp

Added by reub77 on Fri, 03 Dec 2021 04:44:21 +0200