C# WebSoket服务器

发布于:2024-04-11 ⋅ 阅读:(62) ⋅ 点赞:(0)

在这里插入图片描述

web Soket 服务端

1Visual Studio 新建控制台应用程序。

在这里插入图片描述

2添加Fleck

在这里插入图片描述

3编写服务器

static void Main(string[] args)
        {
            FleckLog.Level = LogLevel.Debug;
            var allSockets = new List<IWebSocketConnection>();
            var server = new WebSocketServer("ws://172.16.6.133:7080");
            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    Console.WriteLine("客户端连接成功!");
                    allSockets.Add(socket);
                    Console.WriteLine("当前客户端数量:" + allSockets.ToList().Count);
                };
                socket.OnClose = () =>
                {
                    Console.WriteLine("客户端已经关闭!");
                    allSockets.Remove(socket);
                    Console.WriteLine("当前客户端数量:" + allSockets.ToList().Count);
                };
                //收到消息时
                socket.OnMessage = message =>
                {
                    Console.WriteLine(message);
                    allSockets.ToList().ForEach(s => s.Send("服务器收到了你的消息是:"+message));
                };
            });

            //读取输入消息
            var input = Console.ReadLine();
            //当消息不为“exit"时,则进入死循环
            while (input != "exit")
            {
                //遍历所有的socket客户端,给每个客户端发送消息
                foreach (var socket in allSockets.ToList())
                {
                    socket.Send(input);
                }
                input = Console.ReadLine();
            }
        }

4 web 前端连接

<html>
	 <head>
		<meta charset = "utf-8">
		  <meta name = "viewport" content = "width=device-width, initial-scale=1.0">
		  <title> AAAA </title>
		  <button onclick="sendSoketmess();">发送</button>
	 </head>
	 
	 <body>
	 </body>
</html>
			
<script src = "http://code.jquery.com/jquery-2.1.1.min.js" ></script>
<SCRIPT>
        var ws = null;
		//连接WTS,WebSoket
		function ConnectWebSoket(ip, port) {
			if ("WebSocket" in window) {
						SocketAdd = "ws://" + ip + ":" + port;
						if (ws == null)
						{
							ws = new WebSocket(SocketAdd);
						}
						ws.onopen = function() {//建立链接
							$("body").append("WebSocket已结连接!<br/> ");
						};
						ws.onmessage = function(evt) {//收到消息
							if (evt.data != "PING")
							{
							 $("body").append("WebSocket收到信息:<br/> " + decodeUnicode(evt.data) + "<br/> ");
							}
						}
						ws.onerror = function(event) {
							console.log("Wts Soket连接失败!请检查config中wts地址WtsServerAdd配置!");
							ws = null;
							setTimeout(ConnectWebSoket, 11000);//异常进行重新连接
						};
				} else {
							alert("您的浏览器不支持 WebSocket不能发送该命令,请尝试其他浏览器!");
				}
		}
        ConnectWebSoket("172.16.6.133",7080);
		//Unicode 转 中文
		function decodeUnicode(str)
		{
			str = str.replace(/\\/g, "%");
			// 转换中文
			str = unescape(str);
			// 将其他受影响的转换回原来
			str = str.replace(/%/g, "\\");
			// 对网址的链接进行处理
			str = str.replace(/\\/g, "");
			return str;
		}
		//发送消息
		function sendSoketmess(){
		   ws.send("hello Websoket!,你好!");
		}
</SCRIPT>

5效果

运行exe
在这里插入图片描述