示例程序的主要功能,服务端不停的发送字符串,客户端接收字符串。
服务端,使用Fleck组件,通过nuget方式引用,控制台程序。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Fleck;
namespace websocketserver
{
class Program
{
static void Main(string[] args)
{
FleckLog.Level = LogLevel.Debug;
var allSockets = new List<IWebSocketConnection>();
var server = new WebSocketServer("ws://0.0.0.0:6666");
server.Start(socket =>
{
socket.OnOpen = () =>
{
Console.WriteLine("Open!");
allSockets.Add(socket);
};
socket.OnClose = () =>
{
Console.WriteLine("Close!");
allSockets.Remove(socket);
};
socket.OnMessage = message =>
{
Console.WriteLine(message);
allSockets.ToList().ForEach(s => s.Send("Echo: " + message));
};
});
//var input = Console.ReadLine();
//while (input != "exit")
//{
// foreach (var socket in allSockets.ToList())
// {
// socket.Send(input);
// }
// input = Console.ReadLine();
//}
while (true)
{
foreach (var socket in allSockets.ToList())
{
string input = "hello world";
socket.Send(input);
}
Thread.Sleep(1000);
}
}
}
}
c# 客户端 控制台程序
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace websocketclient
{
class Program
{
static ClientWebSocket clientWebSocket = new ClientWebSocket();
public static void Main(string[] args)
{
clientWebSocket.ConnectAsync(new Uri("ws://localhost:6666"), CancellationToken.None).Wait();//
//发送消息
//while (true)
//{
// ArraySegment<byte> bytesToSend = new ArraySegment<byte>(Encoding.UTF8.GetBytes("ok"));
// clientWebSocket.SendAsync(bytesToSend, WebSocketMessageType.Text, true, CancellationToken.None).Wait();
// Thread.Sleep(1000);
//}
//RunWebSocketClient();
receiveMsg();
Console.ReadKey();
}
public static async Task receiveMsg()
{
while (true)
{
var result = new byte[1024];
await clientWebSocket.ReceiveAsync(new ArraySegment<byte>(result), new CancellationToken());//接受数据
//var lastbyte = ByteCut(result, 0x00);
//var str = Encoding.UTF8.GetString(lastbyte, 0, lastbyte.Length);
Console.WriteLine("Received message: " + Encoding.UTF8.GetString(result, 0, result.Length));
Thread.Sleep(1000);
}
}
public static async Task RunWebSocketClient()
{
ClientWebSocket websocket = new ClientWebSocket();
string url = "ws://localhost:6666/";
Console.WriteLine("Connecting to: " + url);
await websocket.ConnectAsync(new Uri(url), CancellationToken.None);
string message = "Hello World";
Console.WriteLine("Sending message: " + message);
byte[] messageBytes = Encoding.UTF8.GetBytes(message);
await websocket.SendAsync(new ArraySegment<byte>(messageBytes), WebSocketMessageType.Text, true, CancellationToken.None);
byte[] incomingData = new byte[1024];
WebSocketReceiveResult result = await websocket.ReceiveAsync(new ArraySegment<byte>(incomingData), CancellationToken.None);
if (result.CloseStatus.HasValue)
{
Console.WriteLine("Closed; Status: " + result.CloseStatus + ", " + result.CloseStatusDescription);
}
else
{
Console.WriteLine("Received message: " + Encoding.UTF8.GetString(incomingData, 0, result.Count));
}
}
}
}
本文的c#服务端实现参考了 https://blog.csdn.net/ieeso/article/details/112121950
该文章包含浏览器端的客户端实现。