1

I found a great websocket tutorial. If the server get a message, then the server decodes it, and writes to the console, and after that the server sends it back to the client.

  var firstByte = data[0],  
      secondByte = data[1];

  if(!(firstByte & 0x81)) socket.end();
  if(!(secondByte & 0x80)) socket.end();

  var length = secondByte & 0x7f;

  if(length < 126){  
    var mask = data.slice(2,6);  
    var text = data.slice(6);  
  }  

  if(length == 126){  
    var mask = data.slice(4,8);
    var text = data.slice(8);  
  }

  var unMaskedText = new Buffer(text.length);  
    for(var i=0;i<text.length;i++){  
      unMaskedText[i] = text[i] ^ mask[i%4];  
  }  

  console.log(unMaskedText.toString());

  if(unMaskedText.length > 125)  
   var newFrame = new Buffer(4);  
  else  
   var newFrame = new Buffer(2);

  newFrame[0] = 0x81; 

  if(unMaskedText.length > 125){  

  newFrame[1] = 126;  

  var length = unMaskedText.length;  

  newFrame[2] = length >> 8;  
  newFrame[3] = length & 0xFF; //1111 1111  


  } else {  

  newFrame[1] = unMaskedText.length;  

  socket.write(newFrame, 'binary');  
  socket.write(unMaskedText, 'utf8');  
  }

It works, but I would like to send custom messages, not just what the client sent me.

Uw001
  • 363
  • 1
  • 5
  • 12
  • Perhaps you find this wiki answer interesting: http://stackoverflow.com/questions/8125507/how-can-i-send-and-receive-websocket-messages. – pimvdb Nov 21 '11 at 16:24
  • but what shound I modify in my code? – Uw001 Nov 21 '11 at 16:28
  • Looking at it, why can't you send something else than `unMaskedText` instead? E.g. just overwrite `unMaskedText` before doing the send calculations. – pimvdb Nov 21 '11 at 16:37
  • after console.log... I wrote unMaskedText = "welcome"; it works, but when I use some special character, then it crashes. for example: unMaskedText = "welcome: ő"; – Uw001 Nov 21 '11 at 16:46
  • 1
    Oops, I meant `new Buffer("welcome ...")`. That should take care of encoding. – pimvdb Nov 21 '11 at 16:52
  • i was able to use your post to finally finish my hello world. took a week because the net is littered with out of date tutorials. http://pastebin.com/MMXiXYNA ... ondata length > 125 is probably broke. – user1873073 Jan 29 '13 at 05:07

1 Answers1

1

I'll post it as an answer just for clarity.

You should change unMaskedText to a buffer representing the text you want to send, after displaying the received data but before doing calculations for the data to send. E.g.

unMaskedText = new Buffer("test");
pimvdb
  • 151,816
  • 78
  • 307
  • 352