2 Star 4 Fork 0

冰凌呀/CSharp WebSocket Demo

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
Program.cs 3.43 KB
一键复制 编辑 原始数据 按行查看 历史
冰凌呀 提交于 2023-02-08 17:53 +08:00 . 添加项目文件。
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Fleck;
namespace CSharp_WebSocket_Demo
{
class Program
{
static void Main(string[] args)
{
//服务器地址
string ip = "127.0.0.1";
//服务端口
int port = 80;
//多线程安全的字典,存储客户端
//键:客户端ip:port
//值:客户端对象
ConcurrentDictionary<string, IWebSocketConnection> webSocketConnectionDictionary = new ConcurrentDictionary<string, IWebSocketConnection>();
//服务端
WebSocketServer webSocketServer = new WebSocketServer($"ws://{ip}:{port}");
//出错后自动重启
webSocketServer.RestartAfterListenError = true;
//开启服务
webSocketServer.Start(socket =>
{
string key = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
//客户端连接上事件
socket.OnOpen = () =>
{
Console.WriteLine($"客户端【{key}】连接上服务器");
//尝试添加到字典中
webSocketConnectionDictionary.TryAdd(key, socket);
Console.WriteLine($"当前客户端连接数:{webSocketConnectionDictionary.Count}");
};
//服务关闭事件
socket.OnClose = () =>
{
Console.WriteLine($"客户端【{key}】断开连接");
//尝试从字典中移除
webSocketConnectionDictionary.TryRemove(key, out _);
Console.WriteLine($"当前客户端连接数:{webSocketConnectionDictionary.Count}");
};
//服务器出错事件
socket.OnError = (Exception e) =>
{
Console.WriteLine($"客户端【{key}】连接出错");
//尝试从字典中移除
webSocketConnectionDictionary.TryRemove(key, out _);
Console.WriteLine($"当前客户端连接数:{webSocketConnectionDictionary.Count}");
};
//服务器接到客户端消息事件
socket.OnMessage = (string msg) =>
{
Console.WriteLine($"客户端【{key}】发来消息:{msg}");
//给所有客户端返回该消息,实现聊天功能
foreach (IWebSocketConnection webSocketConnection in webSocketConnectionDictionary.Values)
{
try
{
webSocketConnection.Send($"【{key}】:msg");
}
catch (Exception e)
{
Console.WriteLine($"尝试给{webSocketConnection.ConnectionInfo.ClientIpAddress}:{webSocketConnection.ConnectionInfo.ClientPort}发送消息发生异常");
Console.WriteLine(e.StackTrace);
}
}
};
});
Console.WriteLine($"服务端开启 ws://{ip}:{port}");
//防止程序一闪而过
Console.ReadKey();
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C#
1
https://gitee.com/bingling_ice-cream/csharp-web-socket-demo.git
git@gitee.com:bingling_ice-cream/csharp-web-socket-demo.git
bingling_ice-cream
csharp-web-socket-demo
CSharp WebSocket Demo
master

搜索帮助