TCP服务端实现并发

服务端

import socket
from threading import Thread

# 生成服务端
server = socket.socket()
# 确定服务端地址
server.bind(('127.0.0.1', 8889))
# 设置半连接池
server.listen(5)


def talk(sock):
    while True:
        try:
            msg = sock.recv(1024)
            if not msg: break
            print(msg.decode('utf8'))
            sock.send(msg + b'haha')
        except ConnectionResetError as e:
            print(e)
            break
    sock.close()


while True:
    sock, address = server.accept()
    print(address)
    # 开设多线程
    t = Thread(target=talk, args=(sock,))
    t.start()

客户端

import socket

client = socket.socket()
client.connect(('127.0.0.1', 8889))

while True:
    msg = input('请输入您要发送的信息(按q退出)>>>:').strip()
    if not msg: continue
    if msg.lower() == 'q': break
    client.send(msg.encode('utf8'))
    data = client.recv(1024)
    print(data.decode('utf8'))
client.close()

image

posted @ 2022-01-15 15:36  zong涵  阅读(52)  评论(0编辑  收藏  举报