1

I'm building a TCP server using the SocketServer module in python.

As it seems to me, SocketServer.TCPServer functionality is destined to reply to a client that sent a request to the server but not for random communication between the server and the client. For example - Chat between the server and the client..

Is there any way to just send a message to some client registered to the server?

My code for now:

import SocketServer
import chathandler
import threading

PORT = 12345

def do_main():
    global httpd

    Handler = chathandler.ChatHandler

    httpd = SocketServer.TCPServer(("", PORT), Handler)

    print "Serving at port:", PORT
    httpd.serve_forever()

if __name__ == '__main__':
    server_thread = threading.Thread(target = do_main)
    server_thread.start()

    while True:
        print "Send message to the clients"
        s = raw_input(": ")
        # TODO: Send the message!

In this example i want to send the message to all the clients connected to the server.

Thank you!

Shir
  • 1,157
  • 13
  • 35
user3848844
  • 509
  • 6
  • 20
  • Can you please explain which functionality are you thinking to provide using this thing. –  Oct 11 '14 at 14:17
  • The basic use i can find for this is a chat between 2 or more clients and the server as a relaying station. When it gets message from one client it needs to pass it to all the other clients. – user3848844 Oct 11 '14 at 14:57

1 Answers1

0

The way I solved this is by using HTTP persistent connection. As can be quoted from the article:

HTTP persistent connection, also called HTTP keep-alive, or HTTP connection reuse, is the idea of using a single TCP connection to send and receive multiple HTTP requests/responses, as opposed to opening a new connection for every single request/response pair.

BaseHttpRequestHandler class (which ChatHandler inherits from) has a member called "protocol_version" which as we can see in its documentation:

This specifies the HTTP protocol version used in responses. If set to 'HTTP/1.1', the server will permit HTTP persistent connections; however, your server must then include an accurate Content-Length header (using send_header()) in all of its responses to clients. For backwards compatibility, the setting defaults to 'HTTP/1.0'.

so, by assigning Handler.protocol_version = 'HTTP/1.1', the connection won't be closed immediately after processing one request, but will stay to process other requests as well. So the last thing i done, is to override TCPServer's get_request and close_request methods.

get_request is called to accept a connection.

close_request is called to close a connection.

In get_request i added a command after accepting the connection to add the connection to a list of all the current connections and in close_request i added a command to remove this connection from the same list.

user3848844
  • 509
  • 6
  • 20