Implement TCP protocol transmission function with python (server code)

Different from the client code (see my previous blog for the client code), the server needs to bind the port number and set up the monitoring service. There are two more special steps, and two new lines of code are needed to
prepare: windows as On the client, install the network debugging assistant on windows, linux as the server and write the following code, and find out that the ip address on the server (Linux virtual machine) is:
Insert picture description here

import socket

if __name__ == '__main__':
    # 先建立服务端的套接字对象,第一个参数同样是ipv4协议,第二个参数是TCP协议
    tcp_server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 
    # 给程序绑定端口号(相对于客户端代码多的步骤)
    tcp_server_socket.bind(("", 9090))
    # 设置监听服务,等待客户端向服务端发送信息
    # 100:最大等待建立连接的个数
    tcp_server_socket.listen(100)
    # 等待客户端建立连接的请求, 只有客户端和服务端建立连接成功代码才会解阻塞,代码才能继续往下执行
    # 1. 专门和客户端通信的套接字: service_client_socket
    # 2. 客户端的ip地址和端口号: ip_port
    result = tcp_server_socket.accept()
    print(result)
    # 关闭服务端的套接字, 终止和客户端提供建立连接请求的服务
    tcp_server_socket.close()

When the program is run at this time, the program will stop in the accept method and wait for the client to send a request. At this time, open the network debugging assistant:
Insert picture description here
click on the connection, and then return to the virtual machine. You can see the following code:
Insert picture description here
Copy as follows:
(<socket.socket fd= 4, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('192.168.52.128', 9090), raddr=('192.168.52.1', 50036)>, ('192.168.52.1', 50036))
This output is a tuple, the first parameter is a new socket object , and the following is the request from which ip address, that is, the client. At this time, open cmd and enter ipconfig to check Get the local ip:
Insert picture description here
Note : The socket object at this time is a new socket object, not the previous tcp_server_socket object. The bind (bound) socket can be understood as a passive socket at any time Ready to receive messages from the client can be understood as the previous socket object generates a new object to take over the new task. If there is a new message from the client, then tcp_server_socket will generate a new socket object To take over the new task.

Guess you like

Origin blog.csdn.net/weixin_48445640/article/details/108892957