Shir
Shir

Reputation: 1207

Python SocketServer send message from server

I use a TCP server in python, that implements this class:

class ThreadedTCPServer(SocketServer.ThreadingTCPServer):
    pass

The normal use of it works perfect (initiating the server, handling requests and so on).

Now- I need to send a message to the clients, outside of the handle function in the TcpRequestHandler(SocketServer.BaseRequestHandler) class.

I tried to use the following trick, of using the internal socket of the server (it works for UDP)-

tcp_server.client_socket.send(message)

But I get this error message-

socket.error: [Errno 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied

So I assume it is not possible for TCP.

Is there any other way to do it? I assume some servers need to send messages to their client sometimes (that are not just responses to requests), but I couldn't find a good way.

Thanks!

Upvotes: 1

Views: 1038

Answers (1)

mjr104
mjr104

Reputation: 193

You have two general options with TCP:

  1. Send a message to the client out of band (OOB). In this, the server connects separately to the client and the roles are reversed. The client has to listen on a port for OOB messages and acts as a server in this regard. From your problem description you don’t want to do this, which is fine.
  2. Implement a protocol where the server can send messages to the client in response to incoming messages. You will need a way to multiplex the extra messages along with any expected return value to the initiating message. You could implement this with a shared queue on your server. You put messages into this queue outside of your handler and then when the handler is responding to messages you consume from the queue and insert them into the response.

If that sounds like something you are interested in I could write some example code later.

There are pros & cons between both approaches:

In (1) you have more socket connections to manage and you expose the client host to connections which you might not desire. The protocols are simpler because they are not multiplexed.

In (2) you only have a single TCP stream but you have to multiplex your OOB message. You also have increased latency if the client is not regularly contacting the server.

Hope that helps.

Upvotes: 3

Related Questions