运维开发网
广告位招商联系QQ:123077622
 
广告位招商联系QQ:123077622

TCP下的套接字与并发编程

运维开发网 https://www.qedev.com 2020-07-25 15:47 出处:网络 作者:运维开发网整理
# 服务端.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
# 服务端.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()

扫码领视频副本.gif

0

精彩评论

暂无评论...
验证码 换一张
取 消