Skip to content

Instantly share code, notes, and snippets.

@rfunix
Created July 31, 2017 15:01
Show Gist options
  • Select an option

  • Save rfunix/49ec8636b88000cf7bc3dbb6fd4935d2 to your computer and use it in GitHub Desktop.

Select an option

Save rfunix/49ec8636b88000cf7bc3dbb6fd4935d2 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace PrinterWebSocket
{
class Program
{
static void Main(string[] args)
{
var server = new TcpListener(IPAddress.Parse("127.0.0.1"), 5656);
server.Start();
Console.WriteLine("Server has started on 127.0.0.1:5656.{0}Waiting for a connection...", Environment.NewLine);
var 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(
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);
}
Console.WriteLine(data);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment