TCP下的套接字与并发编程

# 服务端.py
import socket
server = socket.socket()
server.bind(('127.0.0.1',9999))

server.listen(5)
while True:
    conn,addr = server.accept()

    while True:
        try:
            data = conn.recv(1024).decode('utf-8')
            if len(data) == 0: break
            print(data)
            msg = input('请输入消息:').strip()
            conn.send(msg.encode('utf-8'))

        except Exception as e :
            print(e)
            break
    conn.close()
    
# 客户端.py
from threading import Thread
import socket

client = socket.socket()
client.connect(('127.0.0.1',9999))
def func(name):
    while True:
        msg = input('输入消息:').strip()
        if len(msg) == 0:break
        msg1 = f"{name}发来消息:{msg}"
        client.send(msg1.encode('utf-8'))

        data = client.recv(1024).decode('utf-8')
        print(data)

if __name__ == '__main__':
    for i in range(100):
        t = Thread(target=func,args=(f'客户{i}',))
        t.start()
相关文章
相关标签/搜索