介绍
Python 实现TPC Socket服务端
python版本: Python 3.11.5
代码
import socket from abc import ABC, abstractmethod class TPCSocketServer(ABC): def __init__(self): self.__tcpSock = None def createServer(self, ip :str, port :int): self.__tcpSock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) self.__tcpSock.bind((ip, port)) def startServer(self): self.__tcpSock.listen(5) def listenServer(self): connect, address = self.__tcpSock.accept() self.handleConnect(connect, address) if(connect): connect.close() @abstractmethod def handleConnect(self, connect, address): pass def closeServer(self): self.__tcpSock.close()
示例
from TPCSocket import TPCSocketServer as TpcServer class Server(TpcServer): def handleConnect(self, connect, address): print(connect,address,connect.recv(1024).decode("utf-8")) connect.send(b"hellos") server = Server() server.createServer("127.0.0.1", 3003) server.startServer() server.listenServer() server.closeServer()