Skip to content

Instantly share code, notes, and snippets.

@Lutando
Created January 18, 2018 07:52
Show Gist options
  • Save Lutando/977709ea24d1b7e502e00bfd619d81c9 to your computer and use it in GitHub Desktop.
Save Lutando/977709ea24d1b7e502e00bfd619d81c9 to your computer and use it in GitHub Desktop.
public static class WebSockets
{
public static void Main(string[] args)
{
RunWebSockets().GetAwaiter().GetResult();
}
private static async Task RunWebSockets()
{
var ws = new ClientWebSocket(); //------v please use a fresh token to test out this is just a PoC client
ws.Options.SetRequestHeader("Authorization","Bearer d9798e6bdc807397640e9e3c4882ffeb245508caf49dda8a80c0cae966aea7da");
await ws.ConnectAsync(new Uri("ws://localhost:5004/ws"), CancellationToken.None);
Console.WriteLine("Connected");
var sending = Task.Run(async () =>
{
string line;
while ((line = Console.ReadLine()) != null)
{
var bytes = Encoding.UTF8.GetBytes(line);
await ws.SendAsync(new ArraySegment<byte>(bytes), WebSocketMessageType.Text, endOfMessage: true, cancellationToken: CancellationToken.None);
}
await ws.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
});
var receiving = Receiving(ws);
await Task.WhenAll(sending, receiving);
}
private static async Task Receiving(ClientWebSocket ws)
{
var buffer = new byte[2048];
while (true)
{
var result = await ws.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Text)
{
Console.WriteLine(Encoding.UTF8.GetString(buffer, 0, result.Count));
}
else if (result.MessageType == WebSocketMessageType.Binary)
{
}
else if (result.MessageType == WebSocketMessageType.Close)
{
await ws.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
break;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment