• 关于websocket做即时通信功能


    本文以网页端实现即时通信,用抢麦器的业务场景来完成即时的效果,需要Fleck.dll和Newtonsoft.Json.dll支持,Fleck是即时通信的核心,Newtonsoft.Json是json格式数据交互解析时用到的,均已上传到我的资源中,也可以在其他地方下载
    1.后端socket服务实现
    以控制台的方式简单实现

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Fleck;
    using Newtonsoft.Json;
    using System.Threading;
    
    namespace WebSocketTest
    {
        class Program
        {
            //存放连接服务器的socket对象
            private static List<IWebSocketConnection> allSockets = new List<IWebSocketConnection>();
            //创建服务,设置服务地址以及端口
            private static WebSocketServer server = new WebSocketServer("ws://0.0.0.0:7181");
            //当前在麦序上的人
            private static List<string> currentMic = new List<string>();
            //倒计时
            private static int timeDown= 15;
    
            static void Main(string[] args)
            {
                FleckLog.Level = LogLevel.Debug;
                //倒计时线程
                Thread timeControl = new Thread(() => {
                    while (true) {
                        //倒计时结束,系统自动下第一个人的麦序
                        if (timeDown == 0)
                        {
                            currentMic.RemoveAt(0);
                            timeDown = 15;
                            MsgClass mc = new MsgClass();
                            mc.op = "systemdownmic";
                            mc.id = "";
                            Console.WriteLine("server:" + JsonConvert.SerializeObject(mc));
                            allSockets.ToList().ForEach(s => s.Send(JsonConvert.SerializeObject(mc)));
                        }
                        //如果麦序上已经没有人,则停止倒计时
                        if (currentMic.Count == 0)
                        {
                            System.Threading.Thread.CurrentThread.Suspend();
                        }
                        System.Threading.Thread.Sleep(1000);
                        timeDown--;
                    }
                });
                server.Start(socket =>{
                    socket.OnOpen = () =>
                    {
                        Console.WriteLine("Open!");
                        allSockets.Add(socket);
                        //对后进来的用户同步当前麦序和计时器状态
                        if (currentMic.Count > 0)
                        {
                            MsgClass mc = new MsgClass();
                            mc.op = "init";
                            mc.currMic = currentMic;
                            mc.id = timeDown.ToString();
                            Console.WriteLine("server:" + JsonConvert.SerializeObject(mc));
                            socket.Send(JsonConvert.SerializeObject(mc));
                        }
                    };
                    socket.OnClose = () =>
                    {
                        Console.WriteLine("Close!");
                        allSockets.Remove(socket);
                    };
                    socket.OnMessage = message =>
                    {
                        Console.WriteLine("client:"+message);
                        MsgClass messageObj =JsonConvert.DeserializeObject<MsgClass>(message);
                        if (messageObj.op == "upmic")
                        {
                            //首次上麦,开始倒计时
                            if (currentMic.Count == 0)
                            {
                                timeDown = 15;
                                if (timeControl.ThreadState == ThreadState.Suspended)
                                {
                                    timeControl.Resume();
                                }
                                else
                                {
                                    timeControl.Start();
                                }
                            }
                            //禁止重复上麦
                            if (currentMic.Contains(messageObj.id))
                            {
                                return;
                            }
                            currentMic.Add(messageObj.id);
                        }
                        else if (messageObj.op == "downmic")
                        {
                            bool isfisrt = false;
                            if (currentMic.IndexOf(messageObj.id) == 0)
                            {
                                isfisrt = true;
                            }
                            currentMic.Remove(messageObj.id);
                            //下麦后没人在麦序上了则停止计时,时间重置为15s
                            if (currentMic.Count == 0)
                            {
                                if (timeControl.ThreadState == ThreadState.Running)
                                {
                                    timeDown = 15;
                                    timeControl.Suspend();
                                }
                            }
                            else if (isfisrt && currentMic.Count > 0)
                            {
                                //选手在第一个位置下麦后,且还有人在麦序,则重新计时
                                timeControl.Suspend();
                                timeDown = 15;
                                timeControl.Resume();
                            }
                        }
                        else if (messageObj.op == "alldownmic")
                        {
                            currentMic.Clear();
                            //全体下麦,清空倒计时,挂起倒计时线程
                            timeDown = 15;
                            timeControl.Suspend();
                        }
                        else if (messageObj.op == "addtime")
                        {
                            //麦序加时
                            timeDown += 15;
                        }
                        else if (messageObj.op == "controlmic")
                        {
                            //控麦下麦
                            if (messageObj.id == "")
                            {
                                return;
                            }
                            //若下的是第一个麦序,且后面没有人了,则停止计时器,重置计时
                            if (currentMic[0] == messageObj.id && currentMic.Count == 1)
                            {
                                timeControl.Suspend();
                                timeDown = 15;
                            }
                            else if (currentMic[0] == messageObj.id && currentMic.Count > 1)
                            {
                                //若下的是第一个麦序,且后面还有人,则重置计时,计时器继续
                                timeControl.Suspend();
                                timeDown = 15;
                                timeControl.Resume();
                            }
                            currentMic.Remove(messageObj.id);
                        }
                        else if (messageObj.op == "pause")
                        {
                            //暂停麦序
                            timeControl.Suspend();
                            //返回当前的倒计时
                            messageObj.id = timeDown.ToString();
                            allSockets.ToList().ForEach(s => s.Send(JsonConvert.SerializeObject(messageObj)));
                            return;
                        }
                        else if (messageObj.op == "start")
                        {
                            //开始麦序
                            timeControl.Resume();
                            //返回当前的倒计时
                            messageObj.id = timeDown.ToString();
                            allSockets.ToList().ForEach(s => s.Send(JsonConvert.SerializeObject(messageObj)));
                            return;
                        }
                        allSockets.ToList().ForEach(s => s.Send(message));
                    };
                });
    
    
                var input = Console.ReadLine();
                while (input != "exit")
                {
                    foreach (var socket in allSockets.ToList())
                    {
                        socket.Send(input);
                    }
                    input = Console.ReadLine();
                }
            }
            
        }
    
        internal class MsgClass
        {
            public string op;
            public string id;
            public List<string> currMic = new List<string>();
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198

    运行该程序
    在这里插入图片描述

    2.前端实现

    DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <html>
    <head>
        <title>抢麦器title>
        <style type="text/css">
            body {
                margin:0px auto;
            }
    
            #main {
                width:500px;
                margin:20px auto;
            }
    
            #content {
                width:250px;
                height:300px;
                border:1px solid black;
            }
            #content div {
                background-color:RGB(248,248,248);
                color:black;
            }
            #content div.select {
                background-color:blue;
                color:white;
            }
        style>
    head>
    <body>
        <div id="main">
            <form id="sendForm">
                您的名字:<input id="myname" value="用户" onchange="powerControl()"/>
                <br /><br />
                <a id="upmic" href="javascript:void(0);" onclick="upMic();">上麦a>  
                <a id="downmic" href="javascript:void(0);" onclick="downMic();">下麦a>          
                <a id="alldownmic" href="javascript:void(0);" onclick="allDownMic();" style="display:none;">全部下麦a>        
                <a id="controlmic" href="javascript:void(0);" onclick="controlMic();" style="display:none;">控麦a>         
                <a id="pauseAndStart" href="javascript:void(0);" onclick="pauseAndStart();" style="display:none;">暂停a>    
                <a id="addtime" href="javascript:void(0);" onclick="addTime();" style="display:none;">加时a>           
                 剩余时间:<span id="time">0span>
                <br />
                <div id="content">
    
                div>
            form>
            <pre id="incomming">pre>
        div>
        
        <script src="js/common/jquery-3.6.0.min.js">script>
        <script type="text/javascript">
            var timeout;//计时器
    
            function powerControl() {
                if ($("#myname").val() == "郭孛") {
                    $("#alldownmic").show();
                    $("#controlmic").show();
                    $("#addtime").show();
                    $("#pauseAndStart").show();
                }
            }
            function pauseAndStart() {
                //主持人控制暂停麦序或开始麦序
                if ($("#myname").val() != "郭孛") {
                    return;
                }
                //没人在麦序上不允许操作开始或暂停
                if ($("#content div").length == 0) {
                    return;
                }
                var json = {};
                if ($("#pauseAndStart").text()=="暂停"){
                    json.op = "pause";
                    $("#pauseAndStart").text("开始");
                }
                else {
                    json.op = "start";
                    $("#pauseAndStart").text("暂停");
                }
                ws.send(JSON.stringify(json));
            }
            function controlMic() {
                //主持人控制下麦
                if ($("#myname").val() != "郭孛") {
                    return;
                }
                if ($("#content div.select").length == 0) {
                    alert("请选中用户后操作!");
                }
                var json = {};
                json.op = "controlmic";
                json.id = $("#content div.select").attr("id");
                ws.send(JSON.stringify(json));
            }
            function upMic()
            {
                //禁止重复上麦
                if ($("#" + $("#myname").val()).length > 0) {
                    return;
                }
                var json = {};
                json.op = "upmic";
                json.id = $("#myname").val();
                ws.send(JSON.stringify(json));
            }
            function downMic() {
                var json = {};
                json.op = "downmic";
                json.id = $("#myname").val();
                ws.send(JSON.stringify(json));
            }
            function allDownMic() {
                //仅指定人员可操作全体下麦
                if ($("#myname").val()!="郭孛") {
                    return;
                }
                var json = {};
                json.op = "alldownmic";
                json.id = $("#myname").val();
                ws.send(JSON.stringify(json));
            }
            function addTime() {
                //仅指定人员可操作加时
                if ($("#myname").val() != "郭孛") {
                    return;
                }
                //加时操作,麦上没人不给加
                if ($("#content div").length == 0) {
                    return;
                }
                var json = {};
                json.op = "addtime";
                json.id = "";
                ws.send(JSON.stringify(json));
            }
            var start = function () {
                var inc = document.getElementById('incomming');
                var wsImpl = window.WebSocket || window.MozWebSocket;
                var form = document.getElementById('sendForm');
                var input = document.getElementById('sendText');
                $("#myname").val(new Date().valueOf());
    
                inc.innerHTML += "正在连接服务器......
    "
    ; // create a new websocket and connect window.ws = new wsImpl('ws://localhost:7181/'); // when data is comming from the server, this method is called ws.onmessage = function (evt) { var data = JSON.parse(evt.data); if (data.op == "init") { //对于后进来的用户应当同步正在进行的数据,如当前麦序上的人以及计时 //填充当前正在麦序上的人 data.currMic.forEach(c=> { $("#content").append("
    " + c + "
    "
    ) }) //初始化计时器 $("#time").text(data.id); timeout = setInterval(function () { var time = +$("#time").text(); $("#time").text(--time); if (time <= 0) { clearInterval(timeout); //由服务端发起系统下麦 /* var json = {}; json.op = "systemdownmic"; json.id = ""; ws.send(JSON.stringify(json)); */ } }, 1000) } if (data.op == "upmic") { //首次上麦,开始倒计时 if ($("#content div").length == 0) { $("#time").text(15); timeout = setInterval(function () { var time = +$("#time").text(); $("#time").text(--time); if (time <= 0) { clearInterval(timeout); //由服务端发起系统下麦 /* var json = {}; json.op = "systemdownmic"; json.id = ""; ws.send(JSON.stringify(json)); */ } },1000) } //上麦操作 if ($("#" + data.id + "").length == 0) { $("#content").append("
    " + data.id + "
    "
    ); } } else if (data.op == "downmic") { var isfirst = false; console.log($("#content div:first").attr("id") == data.id); if ($("#content div:first").attr("id") == data.id) { isfirst = true; } //下麦操作 $("#" + data.id).remove(); //只有第一个人下麦,且麦序上还有人时,则重新倒计时 if (isfirst && $("#content div").length > 0) { $("#time").text(15); } else if ($("#content div").length == 0) { //若麦序上没人了,则停止计时器 $("#time").text(""); clearInterval(timeout); } } else if (data.op == "alldownmic") { //全体下麦 $("#content").empty(); //清空倒计时 $("#time").empty(); clearInterval(timeout); } else if (data.op == "systemdownmic") { //倒计时结束,系统自动下麦,默认下掉排在第一个人的麦序 $("#content div:first").remove(); clearInterval(timeout); $("#pauseAndStart").text("暂停"); //若麦序上还有人,则重新倒计时 if ($("#content div").length > 0) { $("#time").text(15); timeout = setInterval(function () { var time = +$("#time").text(); $("#time").text(--time); if (time <= 0) { clearInterval(timeout); //由服务端发起系统下麦 /* var json = {}; json.op = "systemdownmic"; json.id = ""; ws.send(JSON.stringify(json)); */ } }, 1000) } else { clearInterval(timeout); $("#time").text(""); } } else if (data.op == "addtime") { //加时操作,麦上没人不给加 if ($("#content div").length == 0) { return; } var time = +$("#time").text(); $("#time").text(time + 15); } else if (data.op == "controlmic") { //控麦操作,指定麦上的人员下麦,如果是指定的第一个,且麦上还有人则还需要重新计时 var selectMic = $("#content div[id='" + data.id + "']"); if (selectMic.length == 0) { return; } if (selectMic.attr("id") == $("#content div:first").attr("id") && $("#content div").length > 1) { $("#time").text(15); } else if (selectMic.attr("id") == $("#content div:first").attr("id") && $("#content div").length == 1) { $("#time").text(0); clearInterval(timeout); } selectMic.remove(); } else if (data.op == "pause") { //暂停麦序 clearInterval(timeout); //补正倒计时 $("#time").text(data.id); } else if (data.op == "start") { clearInterval(timeout); //补正倒计时 $("#time").text(data.id); //开始麦序 timeout = setInterval(function () { var time = +$("#time").text(); $("#time").text(--time); if (time <= 0) { clearInterval(timeout); } }, 1000); } //inc.innerHTML += data.id + '
    ';
    }; // when the connection is established, this method is called ws.onopen = function () { inc.innerHTML += '连接成功
    '
    ; }; // when the connection is closed, this method is called ws.onclose = function () { inc.innerHTML += '服务器连接已断开
    '
    ; } form.addEventListener('submit', function (e) { e.preventDefault(); var val = input.value; ws.send(val); input.value = ""; }); $(document).on("click","#content div", function () { $("#content div").removeClass("select"); $(this).addClass("select"); }) } window.onload = start;
    script> body> html>
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283
    • 284
    • 285
    • 286
    • 287
    • 288
    • 289
    • 290
    • 291
    • 292
    • 293
    • 294
    • 295
    • 296
    • 297
    • 298
    • 299
    • 300
    • 301
    • 302
    • 303
    • 304
    • 305
    • 306
    • 307
    • 308
    • 309
    • 310
    • 311
    • 312
    • 313
    • 314
    • 315
    • 316
    • 317
    • 318
    • 319
    • 320
    • 321
    • 322

    前端页面展示
    在这里插入图片描述
    可以看到前端页面打开连接成功后,控制台会同时打印相关信息,表示该页面已成功连接服务器,我们可以多开几个页面后执行相关的功能

    在这里插入图片描述

  • 相关阅读:
    最终稿第5部分理论知识考卷模拟
    openssl websockets
    NodeJS MongoDB⑦
    10分钟了解Flink SQL使用
    3、Shell变量
    【Shell】sh执行脚本报错Syntax error: “(“ unexpected
    JavaFX作业
    股票的涨跌答案
    2024年PMP考试备考经验分享
    (web前端网页制作课作业)使用HTML+CSS制作非物质文化遗产专题网页设计与实现
  • 原文地址:https://blog.csdn.net/listennerBGM/article/details/126936689