Pete.Mertz
Pete.Mertz

Reputation: 1301

WebSocket onmessage not firing

I'm trying to implement my own websocket server and am running into a bit of trouble with the onmessage function in the JavaScript. It just won't fire! I put an alert into it to trigger whenever it was called and the alert never comes up. I've tried on both firefox and chrome to no avail.

As far as I can tell, my server is sending the correct message as well, when I translate it into hex, it matches perfectly with the example in section 5.7 of the documentation here:

http://datatracker.ietf.org/doc/rfc6455/?include_text=1

So I'm not entirely sure what I'm doing wrong. The handshake works fine and so does the close. Here is my code for sending a message currently:

formatted_bytes = []
formatted_bytes.append( 129 )

message_bytes = bytearray( message )

data_start = 0

if ( len( message_bytes ) <= 125 ):
    formatted_bytes.append( len( message_bytes ) )
    start = 2

for byte in message_bytes:
    formatted_bytes.append( byte )

client_socket.send( bytes( formatted_bytes ) )

The server is written in python, forgot to mention that.

Upvotes: 2

Views: 4568

Answers (1)

kanaka
kanaka

Reputation: 73217

This is the same answer as for your other question: Compressed bit must be 0 when sending a message to websocket client

You're problem is that you are using the bytes function in python 2.X but expecting it to work the way it does in python 3.X

python2.6.6:

>>> bytes([129, 19])
'[129, 19]'

python 3:

>>> bytes([129, 19])
b'\x81\x13'

By replacing the send with the following in your server code it works for me in python2.X:

client_socket.send( "".join( [chr(c) for c in formatted_bytes] )

A couple of other notes:

  • The code you linked to is adding 1 to the message length which is incorrect.

  • You should really have the handshake code separate from the normal message parsing code. If somebody happened to send a message which contained "Sec-WebSocket-Key: " you would end up corrupting the stream by sending a raw handshake back again.

Upvotes: 4

Related Questions