socket库 创建socket对象 socket.socket() 绑定端口 socket.bind((host,port)) 开始监听 socket.listen(num) 发送数据 xxx.send(data) 获得客户端的连接 xxx.accept() 返回客户端对象和一个地址数组 ###注意 这里如果不把data编码(data.encode())是不能传输的,会报错 接收数据 xxx.recv() ###注意 这里要把已编码的数据转回来(bytes.decode(data))服务端
import socket import threading host="127.0.0.1" port=9999 server=socket.socket(socket.AF_INET,socket.SOCK_STREAM) server.bind((host,port)) server.listen(5) print(f"[*]Listening on {host}:{port}") def handle(client): request=client.recv(1024) request=bytes.decode(request) print(f"[*]Received:{request}") client.send("ACK".encode()) client.close() while True: client, addr =server.accept() print(f"Getting voice from {addr[0]}:{addr[1]}") client_thread=threading.Thread(target=handle,args=(client,)) client_thread.start()客户端
import socket port=9999 ip="127.0.0.1" client=socket.socket(socket.AF_INET,socket.SOCK_STREAM) client.connect((ip,port)) client.send("hello".encode()) res=bytes.decode(client.recv(4096)) print(res)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)