Network socket programming based on TCP protocol (java realizes C/S communication)

table of Contents

Zero, 1024 special gifts

1. Preface: Introduction to TCP Principles

Two, Socket programming communication

3. TCP server side (specific code)

Four, TCP client (specific code)

5. Communication effect demonstration

6. "Creative" robot: AI core code (specific code) worth one hundred million

Seven, finally


Zero, 1024 special gifts

1024, 1GB, great, come on!

1. Preface: Introduction to TCP Principles

First of all, to ensure the integrity of the article, the theoretical principles of TCP still need to be briefed, which is a bit boring.

TCP (Transmission Control Protocol) is a connection-oriented, reliable, byte stream-based transport layer communication protocol . TCP is designed to adapt to the layered protocol hierarchy that supports multiple network applications. In other words, TCP is a transmission protocol specially designed to provide reliable end-to-end byte streams on unreliable Internet networks . The paired processes in host computers connected to different but interconnected computer communication networks rely on TCP to provide reliable communication services.

The above characteristics of TCP are also the obvious differences from UDP. UDP (User Datagram Protocol) is a connectionless, unreliable communication protocol that does not transmit byte streams . The specific differences can be compared to the previous article:

[ Network Socket programming based on UDP protocol (C/S communication case in java)  ] [ https://blog.csdn.net/Charzous/article/details/109016215 ]

Next, the "three-way handshake" is a well-known word and an important process for establishing a TCP connection. Many articles have detailed interpretations, and this article is a detailed record of this principle, using Java to achieve TCP Socket network communication, including the programming of C/S software architecture, biased to practice, and more interesting!

Two, Socket programming communication

This article uses Java for Socket programming. Java's TCP/IP socket programming encapsulates the underlying details. The programming model is shown in the figure:

We observe from top to bottom, TCP-based communication must have a server server and a client client.

First, establish a connection . There is a socket Socket at each end for communication between the two. The client sends a request to the server to create a socket to connect. The server monitors the request initiated by the client at any time, receives and creates a cracked Socket.

Second, start communication . The input and output streams of the service and the client communicate with each other. Logically, it can be understood that the two sides of the communication process have two streams (output stream and input stream). Logically, two streams can be understood as a full-duplex communication mode of two communication pipes , one is used to send data to the other side, and the other is used to receive data from the other side.

Finally, end the communication . The client ends when accessing the server, disconnects, closes the socket and related resources (input and output streams, etc.). The server monitors the client status and closes connections such as Socket.

Establish communication rules:

The server and the client need to agree on the same rules to ensure normal communication. After the program design, we agreed:

  1. The client connects to the server. After the connection is successful, the server first sends a welcome message to the client;

  2. Each time the client program sends a piece of information to the server, the server receives and sends the information back to the client, and the client receives and displays the information;

  3. When the client sends "bye", the conversation ends.

3. TCP server side (specific code)

The first step is to create a server socket.

Class member variables: ServerSocket serverSocket, monitor port number port;

    private int port =8008;//服务器监听窗口
    private ServerSocket serverSocket;//定义服务器套接字

    public TCPServer() throws IOException{
        serverSocket =new ServerSocket(port);
        System.out.println("服务器启动监听在"+port+"端口...");

    }

The second step is to define the input and output stream method:

    private PrintWriter getWriter(Socket socket) throws IOException{
        //获得输出流缓冲区的地址
        OutputStream socketOut=socket.getOutputStream();
        //网络流写出需要使用flush,这里在printWriter构造方法直接设置为自动flush
        return new PrintWriter(new OutputStreamWriter(socketOut,"utf-8"),true);
    }

    private BufferedReader getReader(Socket socket) throws IOException{
        //获得输入流缓冲区的地址
        InputStream socketIn=socket.getInputStream();
        return new BufferedReader(new InputStreamReader(socketIn,"utf-8"));
    }

 The third step, the core of the server:

//单客户版本,每次只能与一个用户建立通信连接
public void Service(){
    while (true){
        Socket socket=null;
        try {
            //此处程序阻塞,监听并等待用户发起连接,有连接请求就生成一个套接字
            socket=serverSocket.accept();

            //本地服务器控制台显示客户连接的用户信息
            System.out.println("New connection accepted:"+socket.getInetAddress());
            BufferedReader br=getReader(socket);//字符串输入流
            PrintWriter pw=getWriter(socket);//字符串输出流
            pw.println("来自服务器消息:欢迎使用本服务!");

            String msg=null;
            //此处程序阻塞,每次从输入流中读入一行字符串
            while ((msg=br.readLine())!=null){
                //如果用户发送信息为”bye“,就结束通信
                if(msg.equals("bye")){
                    pw.println("来自服务器消息:服务器断开连接,结束服务!");
                    System.out.println("客户端离开。");
                    break;
                }
                pw.println("来自服务器消息:"+msg);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                if (socket!=null)
                    socket.close();//关闭socket连接以及相关的输入输出流
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}

 The key analysis of the code is very clear and easy to understand. It can be seen that the service provided by the server is placed in a While(true). This is because the server program needs to run all the time, so the processing code is generally placed in an infinite loop such as while(true). TCPServer runs once and cannot terminate itself. Run, to terminate its operation, it can only be forced to close (for example, in the IDE environment).

Four, TCP client (specific code)

The first step is to create a client socket, define class construction methods, and implement input and output streams.

    private Socket socket;

    private PrintWriter pw;
    private BufferedReader br;

    public TCPClient(String ip, String port) throws IOException{
        //主动向服务器发起连接,实现TCP三次握手
        //不成功则抛出错误,由调用者处理错误
        socket =new Socket(ip,Integer.parseInt(port));

        //得到网络流输出字节流地址,并封装成网络输出字符流
        OutputStream socketOut=socket.getOutputStream();
        //参数true表示自动flush数据
        pw=new PrintWriter(new OutputStreamWriter(socketOut,"utf-8"),true);

        //得到网络输入字节流地址,并封装成网络输入字符流
        InputStream socketIn=socket.getInputStream();
        br=new BufferedReader(new InputStreamReader(socketIn,"utf-8"));

    }

The second step is to implement network communication sending and receiving methods.

    public void send(String msg){
        //输出字符流,由socket调用系统底层函数,经网卡发送字节流
        pw.println(msg);
    }

    public String receive(){
        String msg=null;
        try {
            //从网络输入字符流中读取信息,每次只能接受一行信息
            //不够一行时(无行结束符),该语句阻塞
            //直到条件满足,程序往下运行
            msg=br.readLine();
        }catch (IOException e){
            e.printStackTrace();
        }
        return msg;
    }

 The third step is to define a method for closing the network connection for external calls.

    public void close(){
        try {
            if (socket!=null)
                socket.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

 The release of a TCP connection also has a "four-way handshake", which must be released after 2MSL. The specific process is as follows:

5. Communication effect demonstration

GIF animation demo:

6. "Creative" robot: AI core code (specific code) worth one hundred million

In this part, we want to implement a "chat bot" with the following effect:

Can't wait to know how to achieve it! It can be called "AI core code worth one hundred million"! ! ? ?

That's it!

 Don't sell it, just one line of code!

msg=msg.replace("?","!").replace("?","!").replace("吗","").replace("吗?","");

 Specifically, if you want to realize how the robot responds, you can adjust the code by itself.

Seven, finally

This article is a detailed record on this principle, using Java to achieve TCP Socket network communication, including the programming of C/S software architecture, biased practice, and more interesting! Friends who read carefully can find that in the core part of the server-side, there is a line of comments stating that the program only supports single-user, that is, single-threaded communication. You can try it. If you open another client to connect to the service, is it because of single-threaded blocking The program is stuck.

The key to this problem lies in the fact that the server and the client agree on the communication rules with each other, otherwise there may be problems. For example, if the server does not send a message to the client after a client connection is successful, the client reads the welcome message statement If the content cannot be read, it will be blocked. Because it is a single thread, even the entire program will be stuck. To solve this problem, wait for the next update!

In addition, the design of the UI interface can refer to the previous blog: [ Network Socket Programming Based on UDP Protocol (C/S Communication Case in Java)  ] [ https://blog.csdn.net/Charzous/article/details/109016215 ]


My CSDN blog: https://blog.csdn.net/Charzous/article/details/109260488

Guess you like

Origin blog.csdn.net/Charzous/article/details/109260488