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()
|
{
|
try
|
{
|
string serverIP = System.Configuration.ConfigurationManager.AppSettings["serverIP"]; //服务器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));
|
};
|
});
|
}
|
catch (Exception ex)
|
{
|
throw new Exception(ex.Message);
|
}
|
|
}
|
|
/// <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;
|
}
|
}
|
}
|