socketserver — A framework for network servers 网络服务器的框架
The socketserver module simplifies the task of writing network servers.该模块简化了编写网络服务器的任务
There are four basic concrete server classes: 有四种基本的具体服务器类
class socketserver.TCPServer(server_address, RequestHandlerClass, bind_and_activate=True)
它使用Internet TCP协议,该协议在客户端和服务器之间提供连续的数据流。如果bind_and_activate为true,则构造函数会自动尝试调用和 。其他参数将传递给基类
class socketserver.UDPServer(server_address, RequestHandlerClass, bind_and_activate=True)
这使用数据报,这些数据报是可能无序到达或在传输过程中丢失的离散信息包。参数与for相同。
class socketserver.UnixStreamServer(server_address, RequestHandlerClass, bind_and_activate=True)
class socketserver.UnixDatagramServer(server_address, RequestHandlerClass, bind_and_activate=True)
这些不经常使用的类类似于TCP和UDP类,但使用Unix域套接字 s; 它们不适用于非Unix平台。参数与for相同
Creating a server requires several steps. First, you must create a request handler class by subclassing the BaseRequestHandler class and overriding its handle() method; this method will process incoming requests. Second, you must instantiate one of the server classes, passing it the server’s address and the request handler class. It is recommended to use the server in a with statement. Then call the handle_request() or serve_forever() method of the server object to process one or many requests. Finally, call server_close() to close the socket (unless you used a with statement).
创建服务器需要几个步骤。首先,您必须通过继承BaseRequestHandler类并重写其handle()方法来创建请求处理程序类; 此方法将处理传入的请求。其次,您必须实例化其中一个服务器类,并将其传递给服务器的地址和请求处理程序类。建议在语句中使用服务器with。然后调用服务器对象的 handle_request()or serve_forever()方法来处理一个或多个请求。最后,调用server_close() 关闭套接字(除非你使用了一个with语句)。
Server classes have the same external methods and attributes, no matter what network protocol they use.
无论使用何种网络协议,服务器类都具有相同的外部方法和属性。
To implement a service, you must derive a class from BaseRequestHandler and redefine its handle() method. You can then run various versions of the service by combining one of the server classes with your request handler class. The request handler class must be different for datagram or stream services. This can be hidden by using the handler subclasses StreamRequestHandler or DatagramRequestHandler.
要实现服务,必须从中派生类BaseRequestHandler 并重新定义其handle()方法。然后,您可以通过将其中一个服务器类与请求处理程序类相结合来运行各种版本的服务。对于数据报或流服务,请求处理程序类必须不同。这可以通过使用处理程序子类StreamRequestHandler或隐藏来隐藏 DatagramRequestHandler。
Of course, you still have to use your head!
server端
import socketserver
class Myserver(socketserver.BaseRequestHandler):
def handle(self):
self.data = self.request.recv(1024).strip()
print('{} wrote: '.format(self.client_address[0]))
print(self.data)
self.request.sendall(self.data.upper())
if __name__ == '__main__':
HOST, PORT = '127.0.0.1', 9999
# 设置allow_reuse_address 允许服务器重用地址
socketserver.TCPServer.allow_reuse_address = True
# 创建一个server,讲服务器地址绑定到127.0.0.1:9000
server = socketserver.TCPServer((HOST, PORT), Myserver)
# 让server永远运行下去,除非强制停止程序
server.serve_forever()
client端
import socket
HOST, PORT = '127.0.0.1', 9999
data = 'hello'
# 创建一个socket连接,SOCK_STREAM代表使用TCP协议
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect((HOST, PORT)) # 链接到客户端
sock.sendall(bytes(data + '\n', 'utf-8')) # 向服务端发送数据
received = str(sock.recv(1024), 'utf-8') # 从服务端接收数据
print('Sent: {}'.format(data))
print('Received: {}'.format(received))
运行结果
127.0.0.1 wrote:
b'hello'
Sent: hello
Received: HELLO