Why Won't the WebSocket.onmessage Event Fire?

Posted by SumWon on Stack Overflow See other posts from Stack Overflow or by SumWon
Published on 2010-04-29T08:52:52Z Indexed on 2010/04/29 8:57 UTC
Read the original article Hit count: 585

Filed under:
|

Hey guys,

After toying around with this for hours, I simply cannot find a solution. I'm working on a WebSocket server using "node.js" for a canvas based online game I'm developing. My game can connect to the server just fine, it accepts the handshake and can even send messages to the server. However, when the server responds to the client, the client doesn't get the message. No errors, nothing, it just sits there peacefully. I've ripped apart my code, trying everything I could think of to fix this, but alas, nothing.

Here's a stripped copy of my server code. As I said before, the handshake works fine, the server receives data fine, but sending data back to the client does not.

var sys = require('sys'),
net = require('net');
var server = net.createServer(function (stream) {
 stream.setEncoding('utf8');
 var shaken = 0;
 stream.addListener('connect', function () {
  sys.puts("New connection from: "+stream.remoteAddress);
 });
 stream.addListener('data', function (data) {
  if (!shaken) {
   sys.puts("Handshaking...");
   //Send handshake:
   stream.write(
   "HTTP/1.1 101 Web Socket Protocol Handshake\r\n"+
   "Upgrade: WebSocket\r\n"+
   "Connection: Upgrade\r\n"+
   "WebSocket-Origin: http://192.168.1.113\r\n"+
   "WebSocket-Location: ws://192.168.1.71:7070/\r\n\r\n");
   shaken=1;
   sys.puts("Handshaking complete.");
  }
  else {
   //Message received, respond with 'testMessage'
   var d = "testMessage";
   var m = '\u0000' + d + '\uffff';
   sys.puts("Sending '"+m+"' to client");
   var result = stream.write(m, "utf8");
   sys.puts(result);
   /*
   Result comes as true, meaning that it pushed the data out.
   Why isn't the client seeing it?!?
   */
  }
 });
 stream.addListener('end', function () {
  sys.puts("Connection closed!");
  stream.end();
 });
});
server.listen(7070);
sys.puts("Server Started!");

© Stack Overflow or respective owner

Related posts about node.js

Related posts about websocket