Receiving Streaming Data Using the ServerSocket Module
serv= SocketServer.TCPServer(("",50008),myTCPServer) serv.serve_forever() . . . line = self.rfile.readline() self.wfile.write("%s: %d bytes successfully received." % (sck, len(line)))
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.
import socket import string class myTCPServer(SocketServer.StreamRequestHandler): def handle (self): while 1: peer = self.connection.getpeername() line = self.rfile.readline() print "%s wrote: %s" % (peer, line) sck = self.connection.getsockname() 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()
22.214.171.124 wrote: Hello 126.96.36.199 wrote: Here is today's weather. 188.8.131.52 wrote: Sunny 184.108.40.206 wrote: High: 75 220.127.116.11 wrote: Low: 58 18.104.22.168 wrote: bye
Output from stream_server.py code