using
System;
using
System.Net.WebSockets;
using
System.Text;
using
System.Threading;
class
Client
{
static
void
Main(
string
[] args)
{
var client =
new
ClientWebSocket();
client.ConnectAsync(
new
Uri(
"ws://echo.websocket.org"
), CancellationToken.None).Wait();
//client.ConnectAsync(new Uri("ws://localhost:4567/ws/"), CancellationToken.None).Wait();
StartReceiving(client);
string
line;
while
((line = Console.ReadLine()) !=
"exit"
)
{
var array =
new
ArraySegment<
byte
>(Encoding.UTF8.GetBytes(line));
client.SendAsync(array, WebSocketMessageType.Text,
true
, CancellationToken.None);
}
}
static
async
void
StartReceiving(ClientWebSocket client)
{
while
(
true
)
{
var array =
new
byte
[4096];
var result = await client.ReceiveAsync(
new
ArraySegment<
byte
>(array), CancellationToken.None);
if
(result.MessageType == WebSocketMessageType.Text)
{
string
msg = Encoding.UTF8.GetString(array, 0, result.Count);
Console.ForegroundColor = ConsoleColor.DarkBlue;
Console.WriteLine(
"--> {0}"
, msg);
Console.ForegroundColor = ConsoleColor.DarkGray;
}
}
}
}