WebSocket+webapi方式推送网页消息

H5端代码



    
    测试 WebSocket


    

测试 WebSocket




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(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 lazy = new Lazy(() => new TestSocket());
        public static TestSocket Instance { get { return lazy.Value; } }
        #endregion

        private string msg = "默认信息";
        Dictionary allSockets = new Dictionary();

        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));
                };
            });
        }

        /// 
        /// 发送消息
        /// 
        /// 
        /// 
        /// 
        public string Send(string userid, string msg)
        {
            var _msg = $"{DateTime.Now.ToString("HH:mm:ss")}:{msg}";
            allSockets[userid].Send(_msg);
            return _msg;
        }
    }
}

你可能感兴趣的:(WebSocket+webapi方式推送网页消息)