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("127.0.0.1"), 8181);
server.Start();
Console.WriteLine("Server has started on 127.0.0.1:8181.{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);
//handshaking
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);
stream.Write(response, 0, response.Length);
}
else
{
Console.WriteLine(data);
}
}
}
}
}
HTML Snippet
<form>
<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>
</form>
<script type="text/javascript">
var start = function () {
var wsImpl = window.WebSocket || window.MozWebSocket;
window.ws = new wsImpl('ws://127.0.0.1:8181/');
ws.onmessage = function (evt) {
console.log(evt.data);
};
ws.onopen = function () {
console.log("Connected");
};
ws.onclose = function () {
console.log("Closed");
};
document.getElementById("sendTextField1").onclick = function() {
sendToSocket(document.getElementById('textField1').value);
};
function sendToSocket(value){
console.log("Sending value to socket " + value + " ");
ws.send(value);
};
}
window.onload = start;
This is what I got from my console
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?