Simple implementation of Socket communication in Python network programming (book at the end of the article)

Socket is an abstract layer of TCP/IP network communication, which provides a series of data interaction operation interfaces, so that developers can no longer pay attention to the details of specific protocol processing, so that their programs can quickly realize network data interaction.

To put it simply, program processes need to communicate through sockets, which is similar to a plug-in, and all processes must be associated to work. As long as it is an application related to the network, sockets must be used.


Socket programming in Python is generally divided into two communication protocols, TCP and UDP, and socket is based on C/S architecture, so socket network programming requires writing client programs and server programs.

TCP communication process

client process

  1. Initializesocket()

  2. Use ip and port number connect() to connect to the server

  3. Use recv() to receive data, send() to send data to interact with the server

  4. closesocket()

Server process

  1. Initializesocket()

  2. Use bind() to bind ip and port number

  3. Use listen() to listen for messages

  4. Get the client's socket address accept()

  5. Use recv() to receive data, send() to send data to interact with the client

  6. closesocket()

Use the socket.socket class in Python to realize TCP program developmentsocket.socket(AddressFamily, Type)

Parameter Description:

  • AddressFamily indicates the type of IP address, divided into TPv4 and IPv6

  • Type indicates the transport protocol type

Common methods are as follows:

function describe
socket() Get the socket class object
bind((hostname, port)) Bind and listen on the port of the specified host
listen() Enable monitoring on the bound port, the parameter indicates the maximum number of connections waiting to be established
accept() Wait for the client to connect, and return the client address after connection
send(data) Send data, data is binary data
recv(buffer) Indicates received data, buffersize is the length of each received data
close() close socket connection
connect((hostname, port)) Set the host name and port number to connect to

Use Python to implement TCP communication code:

Service-Terminal:

import socket
# 创建一个socket对象,默认TCP套接字
s = socket.socket()
# 绑定端口
s.bind(('127.0.0.1',9006))
# 监听端口
s.listen(5)
print("正在连接中……")

# 建立连接之后,持续等待连接
while 1:
    # 阻塞等待连接
    sock,addr = s.accept()
    print(sock,addr)
    # 一直保持发送和接收数据的状态
    while 1:
        text = sock.recv(1024)
        # 客户端发送的数据为空的无效数据
        if len(text.strip()) == 0:
            print("服务端接收到客户端的数据为空")
        else:
            print("收到客户端发送的数据为:{}".format(text.decode()))
            content = input("请输入发送给客户端的信息:")
            # 返回服务端发送的信息
            sock.send(content.encode())

    sock.close()

client:

import socket
# 创建一个socket对象
s1 = socket.socket()
s1.connect(('127.0.0.1', 9006))
# 不断发送和接收数据
while 1:
    send_data = input("客户端要发送的信息:")
    # socket传递的都是bytes类型的数据,需要转换一下
    s1.send(send_data.encode())
    # 接收数据,最大字节数1024,对返回的二进制数据进行解码
    text = s1.recv(1024).decode()
    print("服务端发送的数据:{}".format(text))
    print("------------------------------")

Because network communication needs to find the device in the network through the ip address, and find the port of the corresponding process through the port number, the client ip port must be consistent with the client ip port.

When the connection between the client and the server is established, the port number will not be released immediately after exiting the program, and it needs to wait for about 1-2 minutes. It can be solved by setting port multiplexing ( tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True))

The above code realizes that the TCP server program can only serve one client. If the server program wants to communicate with multiple clients, multi-threading or modules can be used. Socketserver is a repackage socketserverof socket, thus simplifying socket network programming. method.

For more information about the use of python socket, you can check the official documentation to learn:

https://docs.python.org/zh-cn/3/library/socketserver.html#module-socketserver

https://docs.python.org/zh-cn/3/library/socket.html

https://docs.python.org/zh-cn/3/howto/sockets.html

好书推荐《Python数据分析与可视化从入门到精通》本书以“零基础”为起点,系统地介绍了Python在数据处理与可视化分析方面的应用。没有高深理论,每章都以实例为主,读者参考书中源码运行,就能得到与书中一样的结果。相比大而全的书籍资料,本书能让读者尽快上手,开始项目开发,非常适合希望从事Python数据处理与可视化的用户学习。

留言点赞送此书: 点在看本文并留言(本文内容相关、本书相关、其他公众号建议),我将随机挑选一位粉丝包邮送出本书(同一人一个月只有一次机会),送书活动会持续进行,机会多多,大家持续关注,感谢。

Guess you like

Origin blog.csdn.net/XingLongSKY/article/details/120320333