解码网络字符(HTML5 Websocket) [英] Decoding network chars (HTML5 Websocket)

查看:182
本文介绍了解码网络字符(HTML5 Websocket)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用HTML5 websocket(使用 hybi-17 协议)开发网络聊天,但我遇到了字符解码的问题。
这是我通过客户端发送的内容(用户代理:Firefox 7):

I'm trying to develop a webchat with HTML5 websocket (with hybi-17 protocol) but I've some problems with chars decoding. This is what I send through the client (user-agent: Firefox 7):

var socket = new MozWebSocket ('ws://localhost/server.php');
socket.onopen = function () {
  alert ('Opened!');
}

然后,我发送这些数据:

Then, I send these data:

socket.send ('Hello');
socket.send ('World');

这是服务器端代码:

$bytes = @socket_recv ($socket, $buffer, BUFSIZE, 0);

if (($bytes == 0) || ($bytes == 2)) {
  this->disconnect ($socket);
}
else {
  echo $buffer;
}

虽然这是收到的数据回显:

While this is the data recevied echoed:

��6S~g?Y (Hello)
���~����� (World)

如您所见,套接字已打开,数据从客户端传输到服务器。
服务器使用 PHP5 并使用普通的套接字函数来构建连接。

As you can see, the socket is opened and data travels from the client to the server. The server works with PHP5 and uses normal socket functions to build the connection.

如何在一个不可读的字符串中解码人类可读的?

How can I decode that unreadable string in a human readable one?

提前致谢。

推荐答案

你有当他们第一次开始编写使用TCP的代码时,他们犯了一个最常见的错误 - 你忘了实现协议!

You have made one of the most common errors people make when they first start writing code that uses TCP -- you forgot to implement the protocol!

在你的情况下,你忘了它服务器。客户端已经有一个WebSocket实现,您可以通过创建一个'MozWebSocket'对象来请求它。 WebSocket规范说,每帧以0x00字节开头,以0xFF字节结尾,并且中间包含UTF-8数据。服务器中的代码在哪里找到帧的开头和帧的结尾?丢弃0xFF字节的代码在哪里?

In your case, you forgot it in the server. The client already has a WebSocket implementation, and you request it by creating a 'MozWebSocket' object. The WebSocket specification says, "Each frame starts with a 0x00 byte, ends with a 0xFF byte, and contains UTF-8 data in between." Where's the code in the server to find the start of a frame and the end of a frame? Where the code to discard the 0xFF byte?

实际上你必须实现协议。协议规范告诉您如何解码接收的数据。 (在您的情况下,您看到的垃圾数据很可能是协议握手的一部分 - 在此 ^ n:ds [4U 的部分href =http://en.wikipedia.org/wiki/WebSocket#draft-ietf-hybi-thewebsocketprotocol-00 =noreferrer>握手阶段的描述。)

You actually have to implement the protocol. The protocol specification tells you how to decode the received data. (In your case, the data you are seeing as junk is most likely part of the protocol handshake -- the part that looks like ^n:ds[4U in this description of the handkshake phase.)

我很确定你调用PHP脚本来通过Web服务器处理WebSocket调用的方法是行不通的。也就是说,除非您的Web服务器知道如何执行此操作 - WaterSpout phpdaemon

I'm pretty sure your method of invoking a PHP script to handle the WebSocket call through the web server will not work. That is, unless your web server knows how to do this -- WaterSpout and phpdaemon do.

这篇关于解码网络字符(HTML5 Websocket)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆