Code for implementing Socket communication in Python

Server code: the server must be opened first

from socket import *

"""服务端"""
# 主机地址为0.0.0.0,表示绑定本机所有网络接口ip地址
# 等待客户端连接
IP = '127.0.0.1'
# 端口号
PORT = 50000
# 定义一次从socket缓存区中最多读入512
BUFLEN = 512

# 实例化一个socket对象
# 参数 AF_INET表示该socket网络层使用IP协议
# 参数 SOCK_STREAM 表示该socket传输层使用tcp协议
listenSocket = socket(AF_INET,SOCK_STREAM)
listenSocket.bind((IP,PORT))
listenSocket.listen(5)
print(f'服务端启动成功,在{
      
      PORT}端口等待客户连接')

dataSocket, addr = listenSocket.accept()
print('接收一个客户端连接:',addr)

while True:
    info = input('>>>')
    dataSocket.send(bytes(info, encoding='utf-8'))
    recved = dataSocket.recv(BUFLEN)

    if not recved:
        break

    info = recved.decode()
    print(f'收到对方信息{
      
      info}')
    # dataSocket.send(f'服务端接收到信息{info}'.encode())
dataSocket.close()
listenSocket.close()

Client code:

from socket import *

"""客户端"""
# 主机地址为0.0.0.0,表示绑定本机所有网络接口ip地址
# 等待客户端连接
IP = '127.0.0.1'
# 端口号
SERVER_PORT = 50000
BUFLEN = 512

dataSocket = socket(AF_INET, SOCK_STREAM)
dataSocket.connect((IP, SERVER_PORT))


while True:
    recved = dataSocket.recv(BUFLEN)
    if not recved:
        break
    info = recved.decode()
    print(f'收到对方信息{
      
      info}')

dataSocket.close()

operation result

1. The server is opened before the client, and the server after opening is shown in the figure below:
insert image description here
2. The server enters ok and transmits ok to the client.
insert image description here
3. The client receives the transmitted ok
insert image description here

Guess you like

Origin blog.csdn.net/weixin_48501651/article/details/127849586