Vladimir
Vladimir

Reputation: 1

websockets in Firefox 8 and Chrome 15

I try to create my own websocket server. It works good with Safari and Opera, but doesn't work with Firefox 8 and Chrome 15.

For setting connection i use such code

private static void Response(Socket client, string secKey)
{
   string guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
   SHA1 sha = new SHA1CryptoServiceProvider();
   byte[] hash = sha.ComputeHash(Encoding.ASCII.GetBytes(secKey + guid));
   string acceptKey = Convert.ToBase64String(hash);

   client.Send(Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" +   Environment.NewLine));
   client.Send(Encoding.UTF8.GetBytes("Upgrade: WebSocket" + Environment.NewLine));
   client.Send(Encoding.UTF8.GetBytes("Connection: Upgrade" + Environment.NewLine));
   client.Send(Encoding.UTF8.GetBytes("Sec-WebSocket-Accept: " + acceptKey + Environment.NewLine));
}

And for sending messages this one:

var mess = Encoding.UTF8.GetBytes(DateTime.Now.ToString()); 
item.Send(new byte[] { 129 });
item.Send(new byte[] { (byte)mess.Length });
item.Send(mess);

Can anybody help me and point out my mistakes?

Upvotes: 0

Views: 524

Answers (1)

kanaka
kanaka

Reputation: 73091

That code is only for Firefox 8 and Chrome 15 and greater. So I assume your working code with earlier browsers is different than what you posted since they have a different wire format.

There are several issues with your code:

  • You need to pick and send back a protocol if the browser sends a protocol header (which it probably will).
  • You need to send a carriage return + line feed after each header (CR+LF, '\r\n', 0x0D0A).
  • After the final header you need to send an additional carriage return + line feed (i.e. '\r\n\r\n') to indicate completion of the handshake.

Your send algorithm is also overly simplistic (although should work for you example). If the length of the message is more than 126 bytes then you must encode the length into multiple bytes of the frame header.

Also note that for receiving frames, you will need to unmask the payload. The first four bytes of the payload are the masking values. You need to XOR these values to the following payload values. As described in the spec:

j                   = i MOD 4
transformed-octet-i = original-octet-i XOR masking-key-octet-j

Upvotes: 1

Related Questions