J.Doe J.Doe - 1 year ago 242
HTML Question

C# TCP Socket stream message confusion

I'm trying to write a C# TCP server and get my web app connected. This is the tutorial I'm following. Link

I managed to start the server but the message I got from my webapp is encrypted.

C# Snippet

using System;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace Application
class MainClass
public static void Main()
TcpListener server = new TcpListener(IPAddress.Parse(""), 8181);

Console.WriteLine("Server has started on{0}Waiting for a connection...", Environment.NewLine);

TcpClient client = server.AcceptTcpClient();
Console.WriteLine("A client connected.");

NetworkStream stream = client.GetStream();
while (true)
while (!stream.DataAvailable) ;

Byte[] bytes = new Byte[client.Available];

stream.Read(bytes, 0, bytes.Length);

String data = Encoding.UTF8.GetString(bytes);

if (new Regex("^GET").IsMatch(data))
Byte[] response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + Environment.NewLine
+ "Connection: Upgrade" + Environment.NewLine
+ "Upgrade: websocket" + Environment.NewLine
+ "Sec-WebSocket-Accept: " + Convert.ToBase64String(
new Regex("Sec-WebSocket-Key: (.*)").Match(data).Groups[1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
) + Environment.NewLine
+ Environment.NewLine);

stream.Write(response, 0, response.Length);

HTML Snippet

<input id="textField1" type="text" style="margin: 0 5px; width: 200px; height: 40px;" placeholder="Enter data">
<button id="sendTextField1" type="button" class="btn btn-info">Send</button>
<script type="text/javascript">
var start = function () {
var wsImpl = window.WebSocket || window.MozWebSocket;
window.ws = new wsImpl('ws://');

ws.onmessage = function (evt) {
ws.onopen = function () {
ws.onclose = function () {

document.getElementById("sendTextField1").onclick = function() {

function sendToSocket(value){
console.log("Sending value to socket " + value + " ");
window.onload = start;

This is what I got from my console
enter image description here

I have tried to encode the message to another format but no luck at all.

According to this stackoverflow user,

Messages are not sent in raw format, but they have Data Framing.

Is it relevant to the problem I'm having now? Do I need to find a way to deframe the data I got from the app?

Answer Source

Well, this isn't a great start:

String data = Encoding.UTF8.GetString(bytes);

The data sent after the handshake isn't UTF8 text. Parts of it are, but there are binary headers, and there's also something (in RFC6455 at least - possibly not if your client is using Hixie-76) called "Client-to-Server Masking", which means that the data is indeed munged (this is, IIRC, largely to avoid problems with proxy servers, and is not intended to be encryption).

There's also the problem of you looping over the handshake, but: you only handshake once.

Basically, the web-sockets protocol is quite nuanced (and: it is badly/incorrectly implemented by some browsers/versions). Unless you have a very good reason*, I strongly recommend using a library instead of trying to write this by hand. Microsoft provides some level of support in the framework, which should help.

*=I've done this, but for our scenario, the key design reason was scalability - we currently have 464515 open web-socket connections, and the MS implementation just wasn't going to cut it. We made our code freely available, if it helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download