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
using Fleck;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace VueWebApi.Tools
{
    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["FileIP"]; //服务器IP地址
            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;
        }
    }
}