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);
}
}
}
}