WebSocket聊天室

 public static void SocketMethod()
        {
            FleckLog.Level = LogLevel.Debug;
            var allSockets = new List<IWebSocketConnection>();
            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包

以下是前端代码

<style>
			#responseText{
				border: 1px solid grey; width: 350px; height: 300px;overflow-y: auto;display: flex;flex-direction: column;
			}
			#s1{
				margin-left: 10px;
			}
			#s2{
				display: flex;margin-left: 10px;margin-right: 30px;
			}
			#smsg{
				background-color: #eff3f6;border-radius: 8px;padding:8px;margin-top: 5px;
			}
			#client{
				display: flex;flex-direction: column;margin-top: 5px;
			}
			#c1{
				 display: flex;flex-direction: row-reverse;margin-right: 10px;
			}
			#c2{
				 display: flex;flex-direction: row-reverse;margin-right: 10px;margin-left: 30px;
			}
			#cmsg{
				 background-color: #1f8ce8;border-radius: 8px;padding:8px;margin-top: 5px;
			}
</style>
<form onsubmit="return false;"> 
			  <div id="responseText"></div>
		      <br />
		      <input type="text"  name="message"  style="width: 300px" value="" />
			  <div style="margin-top: 10px;">
				 <input type="button"  value="发送消息" onclick="send(this.form.message.value)" />
				 <input  type="button"  onclick="javascript:document.getElementById('responseText').innerHTML=''" value="清空聊天记录" /> 
			  </div> 
</form>
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='<div id="server"><div id="s1">1号 '+h+':'+m+'</div><div id="s2"><div id="smsg">'+event.data	+'</div></div></div>'
						   $("#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='<div id="client"><div id="c1">我 '+h+':'+m+'</div><div id="c2"><div id="cmsg">'+message+'</div></div></div>'
						$("#responseText").append(htm);	
			            socket.send(message)
			        } else {
			          alert("连接没有开启.")
			        }
			    }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值