0

I have recently been trying out websockets as a way to make a simple login system for a website but i have ran into a big problem. whenever I send a message from the websocket, it shows up as a random set of numbers and letters (mostly comes up as ??s??f or something like that).

static TcpListener server = new TcpListener(IPAddress.Any, 8080);
public static void Main()
{

    server.Start();
   serverstart();
}

public static void serverstart()
{
    TcpClient client = server.AcceptTcpClient();

    Console.WriteLine("A client connected.");

    NetworkStream stream = client.GetStream();

    //enter to an infinite cycle to be able to handle every change in stream

     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(
        SHA1.Create().ComputeHash(
            Encoding.UTF8.GetBytes(
                new Regex("Sec-WebSocket-Key: (.*)").Match(data).Groups[1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
            )
        )
    ) + Environment.NewLine
    + Environment.NewLine);
            Console.WriteLine(data);
            stream.Write(response, 0, response.Length);
        }
        else
        {


            Console.WriteLine(data);
            }            


        }
    }
}
2
  • Have you checked the headers to see what Content-Transfer-Encoding (w3.org/Protocols/rfc1341/5_Content-Transfer-Encoding.html) is being used? Are you sure you're receiving UTF8? Commented Feb 14, 2016 at 2:00
  • i am unsure what i am receiving. yet ive tried UTF7 UTF8 UTF32 ACSII and unicode and none of them work Commented Feb 14, 2016 at 11:33

1 Answer 1

1

WebSockets use binary frames to transfer data. In order to read the data you must first parse the Frame Headers to determine how much data was transmitted, whether or not it's masked, etc. One you have that sorted, then you know which bytes in the stream are the ones you want to decode. There's a good reference here.

Basically it's more complicated than you think. Instead of writing your own WebSocketServer, consider using some established projects:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.