python多进程通过socket通讯

服务进程和客户端同体,代码:

import socket
import multiprocessing
 
def handle_server(connection):
    data = connection.recv(1024)
    print("接收到客户端请求:", data.decode(), "\n")
    # 发送数据
    connection.sendall('我是服务器进程,哈哈'.encode('utf-8'))
    connection.close()
    
def handle_client():
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = '127.0.0.1'
    port = 5001
    
    # 连接服务器
    client_socket.connect((host, port))
    
    # 发送数据给服务器
    data = '你好,我是主进程的一个子进程。'
    client_socket.send(data.encode())
    
    # 接收服务器发送的响应数据
    response = client_socket.recv(1024).decode()
    print('服务器的响应:', response)
    
    # 关闭客户端连接
    client_socket.close()
 
def main():
    # 创建TCP/IP socket
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    #server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
 
    # 绑定地址和端口
    server_address = ('127.0.0.1', 5001)
    server_socket.bind(server_address)
 
    # 监听客户端连接
    server_socket.listen(5)
        
    process2 = multiprocessing.Process(target=handle_client, args=())
    process2.start()
    #process2.join()
 
    # 多进程处理连接
    while True:
        connection, client_address = server_socket.accept()
        print("连接地址:", client_address)
        
        process1 = multiprocessing.Process(target=handle_server, args=(connection,))
        process1.start()
        #process1.join()
 
if __name__ == "__main__":
    main()

 

为了测试方便,增加了一个客户端:

import socket

# 创建一个socket对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 获取本地主机名
host = '127.0.0.1'
port = 5001

# 连接服务器
client_socket.connect((host, port))

# 发送数据给服务器
data = '你好,我是另外一个进程。'
client_socket.send(data.encode())

# 接收服务器发送的响应数据
response = client_socket.recv(1024).decode()
print('服务器的响应:', response)

# 关闭客户端连接
client_socket.close()

 

执行结果:

 

posted @ 2024-12-26 09:05  河北大学-徐小波  阅读(4)  评论(0编辑  收藏  举报