Python3 并发编程小练习

实现基于TCP协议套接字,服务端实现接收客户端的连接并发

# server.py
import socket
from threading import Thread

server = socket.socket()
server.bind(
    ('127.0.0.1', 8888)
)
server.listen(5)


def action(conn):
    while True:
        data = conn.recv(1024)
        print(data.decode('utf-8'))
        conn.send(data.upper())


if __name__ == '__main__':
    while True:
        conn, addr = server.accept()
        t = Thread(target=action, args=(conn,))
        t.start()
# client.py
import socket

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

while True:
    msg = input('>>>:')
    if not msg:
        continue
    client.send(msg.encode('utf-8'))
    data = client.recv(1024)
    print(data.decode('utf-8'))
相关文章
相关标签/搜索