1.tcp通讯
serve端
import socket sr = socket.socket() sr.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) sr.bind(('192.168.16.33',8088)) sr.listen() while True: try: conn,addr = sr.accept() while 1: msg = input('>>>:').strip() conn.send(msg.encode('utf-8')) if msg == 'q': break msg = conn.recv(1024) if msg == b'q': break print(msg.decode('utf-8')) conn.close() except UnicodeDecodeError: pass sr.close()
client 端
import socket sl = socket.socket() sl.connect(('192.168.16.33',8088)) while True: msg = sl.recv(1024) if msg == b'q': break print(msg.decode('utf-8')) msg = input('>>>:') sl.send(msg.encode('utf-8')) if msg == 'q': break sl.close()
2.udp协议通讯
serve 端
import socket sk = socket.socket(type=socket.SOCK_DGRAM) sk.bind(('192.168.16.33',8088)) while 1: msg,addr = sk.recvfrom(1024) print(msg.decode('utf-8'),addr) msg = input('>>>') sk.sendto(msg.encode('utf-8'),addr) sk.close()
client 端
import socket sk = socket.socket(type=socket.SOCK_DGRAM) ip_1 = ('192.168.16.33',8088) while 1: msg = input('>>>') sk.sendto(msg.encode('utf-8'),ip_1) msg,addr = sk.recvfrom(1024) print(msg.decode('utf-8'),addr) sk.close()