Pithikos / python-websocket-server

A simple fully working websocket-server in Python with no external dependencies
MIT License
1.14k stars 381 forks source link

Sending to a specific client #66

Open Jawmo opened 5 years ago

Jawmo commented 5 years ago

I noticed that you have instructions to send to a specific client, but when I print our the value of "client", I just get back the current user's information. If I have to use "client" when I use send_message(), how do I actually specify the client ID?

I have to use: send_message(client, "message here.)

If I change "client" to "client['id']" or something, it won't work. How do you actually specify which use it should go to?

DavidSteinmann commented 4 years ago

I just do a for loop looping over all the clients and selecting only the one i want. Here's my function:

def sendMessageToClient(name, message):
    targetClient = None
    for oneClient in server.clients:
        if oneClient['id'] == name:
            targetClient = oneClient
            break
    if targetClient is not None:
        server.send_message(targetClient, message)

Hope it helps

Pithikos commented 3 years ago

This is a bad design decision at the time - using a list instead of a dict.

The workaround is to loop through the clients and once you find your client, use the handler handler.send_text

TheTechRobo commented 1 year ago

Maybe there should be a server.clients_dict or something (in addition to the existing, to keep compatibility)?

Pithikos commented 1 year ago

Maybe there should be a server.clients_dict or something (in addition to the existing, to keep compatibility)?

Yes, probably a clients_by_id with client ID as key. But not something I have the time currently to work on unfortunately

TheTechRobo commented 1 year ago

I might pick this up. Shouldn't be too difficult.

AsgJeold commented 1 year ago

I just do a for loop looping over all the clients and selecting only the one i want. Here's my function:

def sendMessageToClient(name, message):
  targetClient = None
  for oneClient in server.clients:
      if oneClient['id'] == name:
          targetClient = oneClient
          break
  if targetClient is not None:
      server.send_message(targetClient, message)

Hope it helps

Thanks for that. It helped me to solve this problem.