zoukankan      html  css  js  c++  java
  • Fleck学习笔记

    Fleck学习笔记,直接上代码。

    客户端部分

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <html>
    <head>
        <title>websocket client</title>
        <script src="~/Scripts/jquery-3.3.1.min.js"></script>
        <script type="text/javascript">
            $(function () {
                $("#btnConn").unbind().click(webSocketConnect);
                $("#btnSend").unbind().click(function () {
                    $.post("/api/Fleck/Send", { "": JSON.stringify({ "ToUser": $("#txtToUser").val(), "Msg": $("#txtMsg").val() }) }, function (data) {
                        console.log(data);
                    });
                });
            })
            var webSocketConnect = function () {
                var inc = document.getElementById('incomming');
                var wsImpl = window.WebSocket || window.MozWebSocket;
                var form = document.getElementById('sendForm');
                var input = document.getElementById('sendText');
    
                inc.innerHTML += "connecting to server ..<br/>";
                var user = document.getElementById('txtUser');
                // create a new websocket and connect
                window.ws = new wsImpl('ws://localhost:8181/' + user.value);
    
                // when data is comming from the server, this metod is called
                ws.onmessage = function (evt) {
                    inc.innerHTML += evt.data + '<br/>';
                };
    
                // when the connection is established, this method is called
                ws.onopen = function () {
                    inc.innerHTML += '.. connection open<br/>';
                };
    
                // when the connection is closed, this method is called
                ws.onclose = function () {
                    inc.innerHTML += '.. connection closed<br/>';
                }
    
                //form.addEventListener('submit', function (e) {
                //    e.preventDefault();
                //    var val = input.value;
                //    ws.send(val);
                //    input.value = "";
                //});
    
            }
                    //window.onload = webSocketConnect;//可以页面打开自动连接WebSocket,此处想要测试记录user
        </script>
    </head>
    <body>
        @*<form id="sendForm">
                <input id="sendText" placeholder="Text to send" />
            </form>*@
        <pre id="incomming"></pre>
        <input type="text" id="txtUser" /><input type="button" id="btnConn" value="连接" />
    
        <div>
            发送内容:<input type="text" id="txtMsg" />
            接收人:<input type="text" id="txtToUser" /><input type="button" value="发送" id="btnSend" />
        </div>
    </body>
    </html>
    View Code

    服务端部分

    using System.Web.Http;
    using System.Web.Mvc;
    using System.Web.Optimization;
    using System.Web.Routing;
    using WebSocketService.App_Start;
    
    namespace WebSocketService
    {
        public class WebApiApplication : System.Web.HttpApplication
        {
            
            protected void Application_Start()
            {
                AreaRegistration.RegisterAllAreas();
                GlobalConfiguration.Configure(WebApiConfig.Register);
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                BundleConfig.RegisterBundles(BundleTable.Bundles);
                FleckHelper.WebSocketInit();
            }
        }
    }
    View Code
    using Fleck;
    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace WebSocketService.App_Start
    {
        public class FleckHelper
        {
            private static List<IWebSocketConnection> allSockets = new List<IWebSocketConnection>();
            private static Dictionary<string, IWebSocketConnection> socketDic = new Dictionary<string, IWebSocketConnection>();
    
            /// <summary>
            /// WebSocket初始化
            /// </summary>
            public static void WebSocketInit()
            {
                var server = new WebSocketServer("ws://0.0.0.0:8181");//此处端口随意指定,但是不能被占用
                server.Start(socket =>
                {
                    socket.OnOpen = () =>
                    {
                        //Console.WriteLine("Open!");
                        //allSockets.Add(socket);
                        //socketDic.Add(socket.ConnectionInfo.Id.ToString(), socket);//此处想要存储指定的key值,但是无法接收指定参数,仅供测试玩
                        var key = socket.ConnectionInfo.Path.Substring(1);
                        if (!socketDic.Keys.Contains(key))
                        {
                            socketDic.Add(key, socket);//此处想要存储指定的key值,但是无法接收指定参数,仅供测试玩
                        }
                        else
                        {
                            if (socketDic[key] != null)
                            {
                                socketDic[key].Close();
                            }
                            socketDic[key] = socket;
                        }
                    };
                    socket.OnClose = () =>
                    {
                        //Console.WriteLine("Close!");
                        //allSockets.Remove(socket);
                        //socketDic.Remove(socket.ConnectionInfo.Id.ToString());//此处想要删除指定的key值,但是无法接收指定参数,仅供测试玩
                        var key = socket.ConnectionInfo.Path.Substring(1);
                        socketDic.Remove(key);//此处想要删除指定的key值,但是无法接收指定参数,仅供测试玩
                    };
                    socket.OnMessage = message =>
                    {
                        //Console.WriteLine(message);
                        //allSockets.ToList().ForEach(s => s.Send("Echo: " + message));
                    };
                });
            }
    
            /// <summary>
            /// 消息发送
            /// </summary>
            /// <param name="message">自定义json字符串</param>
            public static void Send(string message)
            {
                try
                {
                    var msgInfo = JsonConvert.DeserializeObject<MessageInfo>(message);
                    var toUser = msgInfo.ToUser;
                    var msg = msgInfo.Msg;
                    if (!string.IsNullOrWhiteSpace(toUser))//已指定接收人
                    {
                        if (socketDic.Keys.Contains(toUser))//确认是否有接收人的WebSocket
                        {
                            socketDic[toUser].Send(msg);//发送给指定接收人
                        }
                    }
                    else
                    {
                        socketDic.Values.ToList().ForEach(p => p.Send(msg));//未指定接收人全部发送
                    }
                }
                catch (Exception)
                {
    
                    throw;
                }
            }
    
            /// <summary>
            /// 自定义消息类
            /// </summary>
            public class MessageInfo
            {
                /// <summary>
                /// 接收人
                /// </summary>
                public string ToUser { get; set; }
    
                /// <summary>
                /// 发送信息
                /// </summary>
                public string Msg { get; set; }
            }
        }
    }
    View Code
    using System.Collections.Generic;
    using System.Net.Http;
    using System.Web.Http;
    using WebSocketService.App_Start;
    
    namespace WebSocketService.Controllers
    {
        public class FleckController : ApiController
        {
            // GET: api/Fleck
            public IEnumerable<string> Get()
            {
                return new string[] { "value1", "value2" };
            }
    
            // POST: api/Fleck
            public HttpResponseMessage Post([FromBody]string value)
            {
                FleckHelper.Send(value);
                return Request.CreateResponse("发送成功");
            }
    
            // PUT: api/Fleck/5
            public void Put(int id, [FromBody]string value)
            {
            }
    
            // DELETE: api/Fleck/5
            public void Delete(int id)
            {
            }
        }
    }
    View Code

    注:WebSocket服务端口可以自由指定,但是一定不能被占用,否则会报如下错误:

    以一种访问权限不允许的方式做了一个访问套接字的尝试。

    更丰富的内容可阅读:

    https://github.com/statianzo/Fleck/

    https://www.cnblogs.com/dissun/p/12932239.html

  • 相关阅读:
    Java中的CopyOnWrite
    Collection和Collections的区别
    java中值类型与引用类型的关系
    Xml的用途
    js弹框的3种方法
    文件夹重定向失败解决方案
    网络管理人员经常遇到的十个问题(转载)
    QTP之下拉列表单选框…
    Windows脚本宿主对象模型
    QTP报错“缺少对象WScript”
  • 原文地址:https://www.cnblogs.com/hsybs/p/13518481.html
Copyright © 2011-2022 走看看