Wilk
Wilk

Reputation: 8113

Decoding network chars (HTML5 Websocket)

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');

And this is the server-side code:

$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)

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?

Thanks in advance.

Upvotes: 2

Views: 2854

Answers (2)

Brian
Brian

Reputation: 2305

Using the base server.php and client.html from http://code.google.com/p/phpwebsocket/ along with modification from HTML5 WebSocket with hybi-17 to deal with the single key standard I can successfully send one message to the server before it closes unexpectedly. It's at least a step closer just not sure as of yet why it closes after one successful message.

Upvotes: 0

David Schwartz
David Schwartz

Reputation: 182763

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!

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?

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.)

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.

Upvotes: 5

Related Questions