In addition to the socket module, Python includes the SocketServer module to provide you with TCP, UDP, and UNIX classes that implement servers. These classes have methods that provide you with a much higher level of socket control. To implement a SocketServer to handle streaming requests, first define the class to inherit from the SocketServer.StreamRequestHandler class. To handle the streaming requests, override the handle method to read and process the streaming data. The rfile.readline() function reads the streaming data until a newline character is encountered, and then returns the data as a string. To send data back to the client from the streaming server, use the wfile.write(string) command to write the string back to the client. Once you have defined the server class and overridden the handle method, create the server object by invoking SocketServer.TCPServer(address, handler), where address refers to a tuple in the form of (hostname, port) and handler refers to your defined server class. After the server object has been created, you can start handling connections by invoking the server object's handle_request() or serve_forever() method. Note In addition to the TCPServer method, you can also use the UDPServer, UnixStreamServer, and UnixDatagramServer methods to create other types of servers. import socket import string class myTCPServer(SocketServer.StreamRequestHandler): def handle (self): while 1: peer = self.connection.getpeername()[0] line = self.rfile.readline() print "%s wrote: %s" % (peer, line) sck = self.connection.getsockname()[0] self.wfile.write("%s: %d bytes \ successfuly received." % \ (sck, len(line))) #Create SocketServer object serv = SocketServer.TCPServer(("",50008),myTCPServer) #Activate the server to handle clients serv.serve_forever() stream_server.py 137.65.76.8 wrote: Hello 137.65.76.8 wrote: Here is today's weather. 137.65.76.8 wrote: Sunny 137.65.76.8 wrote: High: 75 137.65.76.8 wrote: Low: 58 137.65.76.8 wrote: bye Output from stream_server.py code |