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

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

服务器端:

import socket
from threading import Thread

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

def action(conn):
    while True:
        try:
            msg_get = conn.recv(1024).decode('utf8')
            if len(msg_get) == 0:
                continue
            if msg_get == 'q':
                break
            print(msg_get)
            conn.send((f'已收到:{msg_get}').encode('utf-8'))
        except Exception as e:
            print(e)
            break


if __name__ == '__main__':
    while True:
        conn, addr = server.accept()
        p = Thread(target=action,args=(conn,))
        p.start()

客户端:

import socket

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

while True:
    send_msg = input('请输入发送的消息:')
    client.send(send_msg.encode('utf-8'))
    if send_msg == 'q':
        break
    data_get = client.recv(1024).decode('utf-8')
    print(data_get)
client.close()

 

posted on 2019-10-22 19:40  啥是py  阅读(164)  评论(0编辑  收藏  举报

导航