Python TCP Server And Client 本文共有3594个字,关键词: 创建TCP连接时,主动发起连接的是客户端,被动响应连接的是服务器。创建Socket时,AF_INET指定使用IPv4协议。如果要用更先进的IPv6,就指定为AF_INET6。SOCK_STREAM指定使用面向流的TCP协议.实现服务端一个接到一个连接时新增一个线程,客户端通过线程发起三个连接Server:import socket import threading import time def tcplink(sock, addr): print(f'Accept new connection from {addr}') sock.send('welcome!'.encode('utf-8')) while True: data = sock.recv(1024) data_str=data.decode('utf-8') time.sleep(0.1) if not data or data.decode('utf-8') == 'exit': break print(f'get data from {addr} --> {data_str}') sock.send(('hello,%s' % data_str).encode('utf-8')) sock.close() print(f'Connection from {addr} closed' ) def main(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = socket.gethostname() port = 8888 s.bind((host, port)) s.listen(5) print('-' * 5, 'START', '-' * 5) while True: sock, addr = s.accept() t = threading.Thread(target=tcplink, args=(sock, addr)) t.start() if __name__=='__main__': main()Clientimport socket import threading def tcpclient(thid): x = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = socket.gethostname() port = 8888 x.connect((host, port)) print(f'client {thid} start' ) print(x.recv(1024).decode('utf-8')) for data in ['小红', '小白', '小丁']: x.send(data.encode('utf-8')) print(str(thid),':get data from server --> ',x.recv(1024).decode('utf-8')) x.send(b'exit') x.close() print(f'client {thid} closed' ) if __name__=='__main__': for i in range(3): xx = threading.Thread(target=tcpclient, args=(i,)) xx.start() 「一键投喂 软糖/蛋糕/布丁/牛奶/冰阔乐!」 赞赏 × 梦白沙 (๑>ڡ<)☆谢谢老板~ 1元 2元 5元 10元 50元 任意金额 2元 使用微信扫描二维码完成支付 版权声明:本文为作者原创,如需转载须联系作者本人同意,未经作者本人同意不得擅自转载。 Python 2022-04-25 评论 323 次浏览