I'm trying to make an async websocket server using c#.
I already have handshake completed, after searching a lot on the internet.
But after the handshake I can't seem to send any data in byte array format :(
This is the code i'm using to send byte[] data to the accepted and connected socket (I check both!)
socket.Send(Encoding.Default.GetBytes("Hello"));
//socket is a System.Net.Sockets.Socket object.
If i try to do this I get this on the client side (I use a chrome extension called "Simple Web Socket Client"):
index.js:15 WebSocket connection to 'ws://localhost:2017/' failed: Invalid frame header
CLOSED: ws://localhost:2017
(Yes 2017 is the port), but why does it say Invalid frame
OK, i get that there is no frame header on the "hello" string, but i can't seem to find what the appropriate header is anywhere on the internet :( and YES I searched and all I get is a seriously confusing specification about RTC!
Anybody here know what I'm doing wrong?
As you can see in this article or in the webSocket specification itself, the webSocket protocol exchanges data in a specific data frame format. You don't just write bytes to a plain socket.
Here's an example of what the frame format looks like:
0 1 2 3
0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
+-+-+-+-+-------+-+-------------+-------------------------------+
|F|R|R|R| opcode|M| Payload len | Extended payload length |
|I|S|S|S| (4) |A| (7) | (16/64) |
|N|V|V|V| |S| | (if payload len==126/127) |
| |1|2|3| |K| | |
+-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
4 5 6 7
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
| Extended payload length continued, if payload len == 127 |
+ - - - - - - - - - - - - - - - +-------------------------------+
8 9 10 11
+ - - - - - - - - - - - - - - - +-------------------------------+
| |Masking-key, if MASK set to 1 |
+-------------------------------+-------------------------------+
12 13 14 15
+-------------------------------+-------------------------------+
| Masking-key (continued) | Payload Data |
+-------------------------------- - - - - - - - - - - - - - - - +
: Payload Data continued ... :
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
| Payload Data continued ... |
+---------------------------------------------------------------+
You must put your data in this format and you must also use the security scheme based on the previously exchanged security credentials. A webSocket is not a plain socket. You must use the webSocket protocol.
FYI, my people don't implement webSocket endpoints from scratch, but rather pick up a library in your selected language that does all that work for you. Then, you can just send bytes and the library will take care of the protocol work for you.