1、TCP简单的一次对话,单通信
客户端:
import socket HOST = 'localhost' PORT = 50006 client = socket.socket(socket.AF_INET,socket.SOCK_STREAM) client.connect((HOST,PORT)) client.sendall(b'hello,python') data = client.recv(1024) print('Received',data)
服务端:
import socket HOST = '' PORT = 50006 sock_server = socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock_server.bind((HOST,PORT)) sock_server.listen(1) conn,addr = sock_server.accept() while True: data =conn.recv(1024) if not data:break conn.send(data)
2、循环收发数据,单通信(TCP)
客户端:
import socket HOST = 'localhost' PORT = 50006 client = socket.socket(socket.AF_INET,socket.SOCK_STREAM) client.connect((HOST,PORT)) while True: cmd = input('>>').strip() if not cmd:break client.send(cmd.encode('utf-8')) data = client.recv(1024) print('Received',data.decode('utf-8'))
服务端:
import socket HOST = '' PORT = 50006 sock_server = socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock_server.bind((HOST,PORT)) sock_server.listen(1) conn,addr = sock_server.accept() while True: data =conn.recv(1024) if not data:break conn.send(data)
3、双方都说话(TCP)
客户端:
import socket HOST = 'localhost' PORT = 50000 client = socket.socket(socket.AF_INET,socket.SOCK_STREAM) client.connect((HOST,PORT)) while True: cmd = input('>>').strip() if not cmd:break client.send(cmd.encode('utf-8')) data = client.recv(1024) print('Received',data.decode('utf-8'))
服务端:
import socket HOST = '' PORT = 50000 sock_server = socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock_server.bind((HOST,PORT)) sock_server.listen(1) while True: conn, addr = sock_server.accept() while True: data =conn.recv(1024) print(f"收到客户端的的数据:>{data.decode('utf-8')}") if not data:break response = input('回复客户端>>').strip() conn.send(response.encode('utf-8'))
4、基于UDP协议实现
客户端:
import socket ip_port = ('127.0.0.1',9000) BUFSIZE = 1024 udp_client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) while True: MSG = input('>>').strip() udp_client.sendto(MSG.encode('utf-8'),ip_port) back_msg,addr = udp_client.recvfrom(BUFSIZE) print(back_msg.decode('utf-8'))
服务端:
import socket ip_socket =('127.0.0.1',9000) BUFSIZE = 1024 udp_server = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) udp_server.bind((ip_socket)) while True: msg,addr = udp_server.recvfrom(BUFSIZE) print(msg.decode('utf-8'),addr) response = input('>>').strip() udp_server.sendto(response.encode('utf-8'),addr)