我正在尝试遵循示例 20.17.4.1。Python 文档中的 SocketServer.TCPServer 。但我收到一个错误:
ImportError: No module named 'ServerSocket'
我正在使用新版本的 Python 并使用 IDLE 来编辑和执行脚本。需要帮助来消除此错误。
在 Python 3 中,SocketServer 模块被重命名为 socketserver。如果你按照 Python 2 的示例代码编写脚本,你需要将模块名从 SocketServer 改为 socketserver。
SocketServer
socketserver
以下是一个完整的示例代码,展示如何在 Python 3 中使用 socketserver.TCPServer:
socketserver.TCPServer
import socketserver class MyTCPHandler(socketserver.BaseRequestHandler): """ The RequestHandler class for our server. It is instantiated once per connection to the server, and must override the handle() method to implement communication to the client. """ def handle(self): # self.request is the TCP socket connected to the client self.data = self.request.recv(1024).strip() print(f"{self.client_address[0]} wrote:") print(self.data) # just send back the same data, but upper-cased self.request.sendall(self.data.upper()) if __name__ == "__main__": HOST, PORT = "localhost", 9999 # Create the server, binding to localhost on port 9999 with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server: # Activate the server; this will keep running until you # interrupt the program with Ctrl-C print(f"Server running on {HOST}:{PORT}") server.serve_forever()
导入模块: python import socketserver 使用 Python 3 中的 socketserver 模块。
python import socketserver
定义请求处理程序类: python class MyTCPHandler(socketserver.BaseRequestHandler): def handle(self): self.data = self.request.recv(1024).strip() print(f"{self.client_address[0]} wrote:") print(self.data) self.request.sendall(self.data.upper())
python class MyTCPHandler(socketserver.BaseRequestHandler): def handle(self): self.data = self.request.recv(1024).strip() print(f"{self.client_address[0]} wrote:") print(self.data) self.request.sendall(self.data.upper())
MyTCPHandler
socketserver.BaseRequestHandler
handle
在 handle 方法中,接收客户端发送的数据并将其转换为大写后发送回客户端。
创建并启动服务器: python if __name__ == "__main__": HOST, PORT = "localhost", 9999 with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server: print(f"Server running on {HOST}:{PORT}") server.serve_forever()
python if __name__ == "__main__": HOST, PORT = "localhost", 9999 with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server: print(f"Server running on {HOST}:{PORT}") server.serve_forever()
HOST
PORT
with
TCPServer
server.serve_forever()
这段代码将启动一个 TCP 服务器,在 localhost 的 9999 端口监听,并将接收到的消息转换为大写后返回给客户端。确保你使用的是 Python 3,并且正确导入了 socketserver 模块。
localhost