基于tcp協(xié)議通信
服務(wù)端
import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
def handle(self):
while True:
try:
data = self.request.recv(1024)
if len(data) == 0: break
print('-->收到客戶端的消息: ', data)
self.request.send(data.upper())
except ConnectionResetError:
break
self.request.close()
if __name__ == '__main__':
server = socketserver.ThreadingTCPServer(('127.0.0.1', 8080), MyTCPHandler)
server.serve_forever()
客戶端 (多個(gè)客戶端代碼一樣)
from socket import *
client = socket(AF_INET, SOCK_STREAM)
client.connect(('127.0.0.1', 8080))
# 通信循環(huán)
while True:
msg = input('>>: ').strip()
if len(msg) == 0: continue
client.send(msg.encode('utf-8'))
data = client.recv(1024)
print(data)
client.close()
基于udp協(xié)議通信
服務(wù)端
import socketserver
class MyUDPHandler(socketserver.BaseRequestHandler):
def handle(self):
data, sock = self.request
sock.sendto(data.upper(), self.client_address)
if __name__ == '__main__':
server = socketserver.ThreadingUDPServer(('127.0.0.1', 8080), MyUDPHandler)
server.serve_forever()
客戶端
from socket import *
client = socket(AF_INET, SOCK_DGRAM)
while True:
client.sendto(b'hello', ('127.0.0.1', 8080))
data, server_address = client.recvfrom(1024)
print(data)