Python "pywbsocket" HTML5 websocket server Configuration Issue?
Hello I am trying to use python's pywebsocket HTML5 server, where i use the given example file which echos back whatever is received.
def web_socket_transfer_data(request):
count = 0
while (count < 1):
line = request.ws_stream.receive_message()
print line
request.ws_stream.send_message(line)
It works fine with one webpage, but if i use two clients (two webpages connection to the same socket server over same ports), the script works the same.
What i am trying to do is to have those messages broadcasted by the socket server of for any message echoed back, should be listened by both cient webpages. But unforutnally it does not w开发者_JAVA百科ork. I am confused as both pages are listening over same socket, then why is it not working.
Is there any workaround or modification i need to do so that i can make the socket server transfer message or broadcast to all its connected clients.
Please help...
With the exception of multicast sockets, all are 1:1 connections. You have to maintain the list of open sockets somewhere, and send the message to each of them. The port you connect to when creating the socket being the same merely means each client is connected to the same service.
Here's how you might add each connection to a list and broadcast to all of them. Of course, I'd strongly recommend having code to handle dead and/or closed connections and remove them from the list as well, I'm just going for the general idea here (especially since I haven't coded in Python for a few years. I based this code snippet on the pywbsocket example code, which is why it's different from yours. Note that I haven't considered thread safety at all either, which should be a concern)
connections = []
def web_socket_do_extra_handshake(request):
connections.append(request);
pass
def web_socket_transfer_data(request):
while True:
line = msgutil.receive_message(request)
for connection in connections[:]:
msgutil.send_message(connection, line)
if line == "Bye":
return
The problem is that the connection variable is reset on every new call, I think.
So I changed the code to initialize the connections variable only if it's not defined yet:
try:
connections
except:
connections = []
Now it should work.
精彩评论