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.

6
  • Perhaps you find this wiki answer interesting: stackoverflow.com/questions/8125507/…. Commented Nov 21, 2011 at 16:24
  • but what shound I modify in my code? Commented Nov 21, 2011 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. Commented Nov 21, 2011 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: ő"; Commented Nov 21, 2011 at 16:46
  • 1
    Oops, I meant new Buffer("welcome ..."). That should take care of encoding. Commented Nov 21, 2011 at 16:52

1 Answer 1

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");
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.