简体   繁体   English

通过WebSockets传输文本的正确方法是什么?

[英]What is the proper way to transmit text through WebSockets?

I'm developing a Web application using WebSockets, so at some point I need to send a text file to the web browser (chrome in this case), but chrome just calls onerror without giving me any clue about what's wrong. 我正在使用WebSockets开发Web应用程序,因此有时需要将文本文件发送到Web浏览器(在本例中为chrome),但是chrome只是调用onerror而没有提供任何有关错误原因的线索。 If I work with FireFox, it just says there was an error, but again, it gives me no real clue. 如果我使用FireFox,它只是说有一个错误,但同样,它也没有给我真正的线索。

At first I though I was doing something wrong on the server side, until I thought: What if I tweek the opcode and tell the socket I'm sending binary data, so I did, and as I imagined no error occurred, chrome got the file and everything was fine, except that there's no way I know to convert binary data into text using JavaScript. 起初,我虽然在服务器端做错了事,但直到我想到:如果我将操作码放到星期并告诉套接字我正在发送二进制数据该怎么办,所以我做到了,而且我以为没有错误发生,chrome得到了文件,一切都很好,只是我无法使用JavaScript将二进制数据转换为文本。 That lead me to write a function to encode the text in such a way that the encoded version contains no special characters, again, no error... so this is obviously a problem of the text itself. 这就导致我编写了一个函数来对文本进行编码,以使编码后的版本不包含任何特殊字符,同样,也没有错误……因此,这显然是文本本身的问题。

Currenlty the only way I've being able to work around is by encoding and decoding the text, however I'm not quite sure this is the right way to do it. Currenlty唯一可以解决的方法是对文本进行编码和解码,但是我不确定这是否是正确的方法。 So I wish to know: is there better way? 所以我想知道:还有更好的方法吗?

First of all, you do not need to decode the frame in Browser. 首先,您不需要在浏览器中解码帧。 It's already decoding the binary message (standard websocket format). 它已经在解码二进制消息(标准的websocket格式)。

I have just committed a working minimal websocket server to github. 我刚刚向github提交了一个最小的websocket服务器。 You can give a try. 你可以试试看。 SGwebsocket SGwebsocket

If you want to implement by yourself you will need RFC6455 reference for decoding and encoding the frames. 如果要自己实现,则需要RFC6455参考来解码和编码帧。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM