WebSocket+webapi方式推送网页消息

2022-01-06  本文已影响0人  软件开发01

H5端代码

<html>
<head>
    <meta charset="UTF-8"></meta>
    <title>测试 WebSocket</title>
</head>
<body>
    <h3>测试 WebSocket</h3>
    <br />
    <!--<input id="text" type="text" />
    <button onclick="send()">发送测试</button>-->
    <hr />
    <button onclick="clos()">关闭连接</button>
    <hr />
    <div id="message"></div>
    <script>
        var userid = 51218;

        var websocket = null;
        if ('WebSocket' in window) {
            websocket = new WebSocket("ws://192.168.4.63:8881/api/Send/getmsg?userid=" + userid);//链接服务器
        } else {
            alert("您的浏览器不支持websocket");
        }
        websocket.onerror = function () {
            setMessageInHtml("send error!");
        }
        websocket.onopen = function () {
            setMessageInHtml("connection success!<br />")
        }
        websocket.onmessage = function (event) {
            setMessageInHtml(event.data);
        }
        websocket.onclose = function () {
            setMessageInHtml("closed websocket!<br /")
        }
        window.onbeforeunload = function () {
            clos();
        }
        function setMessageInHtml(message) {
            document.getElementById('message').innerHTML += message + "<br />";
        }
        function clos() {
            websocket.close(3000, "强制关闭");
        }
        function send() {
            var msg = document.getElementById('text').value;
            websocket.send(msg);
        }
    </script>
</body>
</html> 

webApi服务端代码

SendController.cs

namespace WebApplication4.Controllers
{
    [RoutePrefix("Send")]
    public class SendController : ApiController
    {
        private readonly ClientWebSocket webSocket = new ClientWebSocket();
        private readonly CancellationToken _cancellation = new CancellationToken();

        [HttpGet]
        public async Task SendMsg(string msg)
        {
            await webSocket.ConnectAsync(new Uri("ws://localhost:60518/api/msg"), _cancellation);
            var sendBytes = Encoding.UTF8.GetBytes(msg);//发送的数据
            var bsend = new ArraySegment<byte>(sendBytes);
            await webSocket.SendAsync(bsend, WebSocketMessageType.Binary, true, _cancellation);
            await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "1", _cancellation);
            webSocket.Dispose();
        }

        //http://localhost:port/api/Send/Init
        [HttpGet]
        public string Init()
        {
            TestSocket.Instance.socketServer();
            return "success";
        }

        [HttpGet]
        public string Msg(string userid, string msg)
        {
            var _msg = TestSocket.Instance.Send(userid, msg);
            return _msg;
        }
    }
}

TestSocket.cs

namespace WebApplication4.Models
{
    public class TestSocket
    {
        #region 单例模式
        private static readonly Lazy<TestSocket> lazy = new Lazy<TestSocket>(() => new TestSocket());
        public static TestSocket Instance { get { return lazy.Value; } }
        #endregion

        private string msg = "默认信息";
        Dictionary<string, IWebSocketConnection> allSockets = new Dictionary<string, IWebSocketConnection>();

        public void socketServer()
        {
            string serverIP = System.Configuration.ConfigurationManager.AppSettings["serverIP"];
            var server = new WebSocketServer(serverIP);
            server.Start(socket =>//服务开始
            {
                var userid = socket.ConnectionInfo.Path.Split('?')[1].Split('=')[1];

                socket.OnOpen = () =>
                {
                    Console.WriteLine("Open!");
                    allSockets.Add(userid, socket);
                };
                socket.OnClose = () =>
                {
                    Console.WriteLine("Close!");
                    allSockets.Remove(userid);
                };
                socket.OnMessage = message =>
                {
                    //客户端交互的消息
                    //System.Timers.Timer t = new System.Timers.Timer(10000);//实例化Timer类,设置间隔时间为10000毫秒;
                    //t.Elapsed += new System.Timers.ElapsedEventHandler(theout);//到达时间的时候执行事件;
                    //t.AutoReset = true;//设置是执行一次(false)还是一直执行(true);
                    //t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件;
                    allSockets.ToList().ForEach(s => s.Value.Send("Echo: " + msg));
                };
            });
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public string Send(string userid, string msg)
        {
            var _msg = $"{DateTime.Now.ToString("HH:mm:ss")}:{msg}";
            allSockets[userid].Send(_msg);
            return _msg;
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读