您好,登錄后才能下訂單哦!
最簡單、原始的TCP通信demo
服務端Http請求:
import socket # 創建一個servicesocke serviceSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 給服務器綁定地址(ip地址,端口號) serviceSocket.bind(("192.168.171.1", 80)) print("等待客戶端接入") # sock 是客戶端的socket信息 # addr 是客戶端的地址(ip,端口) sock, addr = serviceSocket.accept() print(f"sock from client:{sock}") print(f"addr of client:{addr}") while True: # 接收客戶端的請求 recvData = sock.recv(1024) print("客戶端說:%s" % (recvData.decode("utf-8"))) sendData = input("服務器說:") # 發送(回復)數據給客戶端 sock.send(sendData.encode("utf-8"))
客戶端Http請求:
import socket # 創建客戶端socket clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 連接服務器 clientSocket.connect(("192.168.171.1", 80)) while True: # 發送消息給服務器 sendData = input("客戶端說:") if sendData == "bye": clientSocket.send(sendData.encode("utf-8")) # 編碼:將數據裝換成二進制形式 break clientSocket.send(sendData.encode("utf-8")) recvData = clientSocket.recv(1024) print("服務器說:%s" % (recvData.decode("utf-8"))) # 解碼:將二進制轉換成字符
1、在TCP中,客戶端的實現流程:
創建客戶端的socket對象建立與服務器之間的聯系發送請求接收數據關閉連接
2、服務端的實現流程:
創建服務端的socket對象綁定服務端的地址設置監聽器等待客戶端的連接接收客戶端的請求返回處理的結果到客戶端
ThreadingTCPServer 多線程多客戶端通信自動重連demo
socketserver繼承圖:
TCPServer
# from socketserver import TCPServer, BaseRequestHandler, ThreadingTCPServer from socketserver import TCPServer, StreamRequestHandler, ThreadingMixIn import traceback # class MyBaseRequestHandler(BaseRequestHandler): class MyBaseRequestHandler(StreamRequestHandler): def handle(self): self.addr = self.request.getpeername() self.server.users[self.addr[1]] = self.request message = "IP " + self.addr[0] + ":" + str(self.addr[1]) + " Connected..." print(message) while True: try: data = self.request.recv(1024).decode('UTF-8', 'ignore').strip() print(f'receive from {self.client_address}:{data}') back_data = (f"response\"" + data + "\":\n").encode("utf8") self.request.sendall(back_data) except: traceback.print_exc() break # 源碼:class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass # 從ThreadingMixIn和TCPServer繼承,實現多線程 class MyThreadingTCPServer(ThreadingMixIn, TCPServer): def __init__(self, server_address, RequestHandlerClass): TCPServer.__init__(self, server_address, RequestHandlerClass) self.users = {} class MyTCPserver(): def __init__(self, server_addr='192.168.1.109', server_port=23): self.server_address = server_addr self.server_port = server_port self.server_tuple = (self.server_address, self.server_port) def run(self): # server = TCPServer(self.server_tuple, MyBaseRequestHandler) server = MyThreadingTCPServer(self.server_tuple, MyBaseRequestHandler) server.serve_forever() if __name__ == '__main__': myserver = MyTCPserver() myserver.run()
在telnet 下開啟開啟兩個客戶端,本電腦的IP為192.168.1.109,開兩個客戶端后,TCPServer的終端出現同一個IP但是不同端口的連接:
TCPClient
import socket import time class MyClient: host = '192.168.1.109' port = 23 bufsiz = 1024 addr = None skt = None def __init__(self, host=None, port=None): if host != None: self.host = host if port != None: self.port = port if self.addr == None: self.addr = (self.host, self.port) self.doConnection() def doConnection(self): try: self.skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) print(self.addr) self.skt.connect(self.addr) except: pass def run(self): while True: try: _time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) self.skt.sendall(f'{_time}:i am clent1 '.encode('utf-8')) data = self.skt.recv(self.bufsiz) print(data.decode('utf-8', 'ignore')) if not data: break print(data.strip()) time.sleep(5) except socket.error: print('socket error, reconnection') # 自動重連 time.sleep(3) self.doConnection() except: print('other error') self.skt.close() myclient = MyClient() myclient.run()
上面用的是telnet工具來作為客戶端,這里是用代碼實現模擬的客戶端。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。