基于TCP通信
import socket server na=socket.socket() na.bind(('127.0.0.1',9000)) na.listen(5) conn.addr=na.accept() conn.recv(1024) conn.send(b'xxx') conn.close() na.close() client import socket qiang=socket.socket() qiang.connect(('127.0.0.1',9000)) qiang.send(b'xx') qiang.recv(1024) qiang.close()
基于UDP通信
server import socket na=socket.socket(type=socket.SOCK_DGRAM) na.bind(('127.0.0.1',9000)) while 1: msg,cli_addr=na.recvfrom(1024) na.sendto(msg,cli_addr) na.close() client import socket qiang=socket.socket(type=socket.SOCK_DGRAM) qiang.sendto(b'msg',('127.0.0.1',9000)) msg,_=qiang.recvfrom(1024) print(msg) qiang.close()