Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Receiving Streaming Data Using the ServerSocket Module

serv= SocketServer.TCPServer(("",50008),myTCPServer)
. . .
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

    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 =

#Activate the server to handle clients

stream_server.py wrote: Hello wrote: Here is today's weather. wrote: Sunny wrote: High: 75 wrote: Low: 58 wrote: bye

Output from stream_server.py code

  • + Share This
  • 🔖 Save To Your Account