WebSocket onmessage 未触发 [英] WebSocket onmessage not firing
问题描述
我正在尝试实现我自己的 websocket 服务器,但在 JavaScript 中的 onmessage 函数遇到了一些麻烦.就是不会火!我将警报放入其中以在调用时触发并且警报永远不会出现.我在 firefox 和 chrome 上都试过了,但无济于事.
据我所知,我的服务器也发送了正确的消息,当我将其转换为十六进制时,它与此处文档第 5.7 节中的示例完全匹配:
http://datatracker.ietf.org/doc/rfc6455/?include_text=1
所以我不完全确定我做错了什么.握手工作正常,关闭也是如此.这是我当前发送消息的代码:
formatted_bytes = []formatted_bytes.append(129)message_bytes = bytearray( 消息)数据开始 = 0如果 ( len( message_bytes ) <= 125 ):formatted_bytes.append(len(message_bytes))开始 = 2对于 message_bytes 中的字节:formatted_bytes.append( 字节 )client_socket.send( bytes( formatted_bytes ) )
服务器是用python写的,忘了说了.
这与您的其他问题的答案相同:向websocket客户端发送消息时压缩位必须为0
你的问题是你在 python 2.X 中使用了 bytes
函数,但希望它像在 python 3.X 中那样工作
python2.6.6:
<预><代码>>>>字节([129, 19])'[129, 19]'蟒蛇 3:
<预><代码>>>>字节([129, 19])b'\x81\x13'通过在您的服务器代码中用以下内容替换发送,它在 python2.X 中对我有用:
client_socket.send( "".join( [chr(c) for c in formatted_bytes] )
其他一些注意事项:
您链接的代码将消息长度加 1,这是不正确的.
你真的应该将握手代码与普通的消息解析代码分开.如果有人碰巧发送了一条包含Sec-WebSocket-Key:"的消息,您最终会再次发送原始握手来破坏流.
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.
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.
这篇关于WebSocket onmessage 未触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!