代码:
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Demo
{
class Program
{
async static Task Main(string[] args)
{
var client = new ClientWebSocket();
client.ConnectAsync(new Uri("ws://echo.websocket.org"), CancellationToken.None).Wait();
StartReceiving(client);
string line;
while ((line = Console.ReadLine()) != "exit")
{
var array = new ArraySegment<byte>(Encoding.UTF8.GetBytes(line));
await 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;
}
}
}
}
}