WebSocket聊天室

 public static void SocketMethod()
        {
            FleckLog.Level = LogLevel.Debug;
            var allSockets = new List();
            var server = new WebSocketServer("ws://0.0.0.0: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();
            } 
        }

后台使用C #的Fleck包

以下是前端代码


if (!window.WebSocket) {
			    window.WebSocket = window.MozWebSocket
			}
				  
					let isClient=false;
			        const socket = new WebSocket("ws://127.0.0.1:7080/ws")
			        socket.onmessage = function (event) {
			           if(!isClient){
						   isClient=true
						   var h=new Date().getHours();
						   var m=new Date().getMinutes();
						   var htm='
1号 '+h+':'+m+'
'+event.data +'
' $("#responseText").append(htm); }else isClient=false; } socket.onopen = function (event) { let ta = document.getElementById("responseText") ta.value = "连接开启!" } socket.onclose = function (event) { let ta = document.getElementById("responseText") ta.value = ta.value + "连接被关闭" } function send(message) { if (!window.WebSocket) { return } if (socket.readyState == WebSocket.OPEN) { isClient=true var h=new Date().getHours(); var m=new Date().getMinutes(); var htm='
我 '+h+':'+m+'
'+message+'
' $("#responseText").append(htm); socket.send(message) } else { alert("连接没有开启.") } }

你可能感兴趣的:(websocket,前端,c#)