You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
94 lines
3.5 KiB
94 lines
3.5 KiB
using Fleck;
|
|
using Newtonsoft.Json;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Configuration;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Container.Common
|
|
{
|
|
public class WebsocketForProgramServer
|
|
{
|
|
//public static ConcurrentDictionary<string, System.Net.WebSockets.WebSocket> _sockets = new ConcurrentDictionary<string, System.Net.WebSockets.WebSocket>();
|
|
public static List<IWebSocketConnection> allSockets = new List<IWebSocketConnection>();
|
|
|
|
private static Class_Log log = new Class_Log(); //日志记录文件
|
|
private static App app = ((App)System.Windows.Application.Current);
|
|
WebSocketServer server = null;
|
|
public void openSocket()
|
|
{
|
|
|
|
try
|
|
{
|
|
allSockets.Clear();
|
|
FleckLog.Level = LogLevel.Debug;
|
|
var ws = "ws://"+app.websocketProgramIP + ":"+ ConfigurationManager.AppSettings["websocketProgramPort"];
|
|
server = new WebSocketServer(ws);
|
|
//RecognizerCLR.setBeamDir(serialPortname, microAngle);
|
|
server.Start(socket =>
|
|
{
|
|
socket.OnOpen = () => //当建立Socket链接时执行此方法
|
|
{
|
|
//var data = socket.ConnectionInfo; //通过data可以获得这个链接传递过来的Cookie信息,用来区分各个链接和用户之间的关系(如果需要后台主动推送信息到某个客户的时候,可以使用Cookie)
|
|
//Console.WriteLine("Open!");
|
|
log.WriteLogFile(JsonConvert.SerializeObject(socket.ConnectionInfo.ClientIpAddress), "socket");
|
|
IWebSocketConnection clearSocket = null;
|
|
foreach (var item in allSockets)
|
|
{
|
|
if (item.ConnectionInfo.ClientIpAddress == socket.ConnectionInfo.ClientIpAddress) {
|
|
clearSocket = item;
|
|
break;
|
|
}
|
|
}
|
|
if (clearSocket != null) {
|
|
allSockets.Remove(clearSocket);
|
|
}
|
|
allSockets.Add(socket);
|
|
//log.WriteLogFile(JsonConvert.SerializeObject(allSockets), "socket");
|
|
log.WriteLogFile(allSockets.Count.ToString(), "GetSyncDevServer");
|
|
};
|
|
|
|
socket.OnClose = () =>// 当关闭Socket链接十执行此方法
|
|
{
|
|
|
|
//Console.WriteLine("Close!");
|
|
allSockets.Remove(socket);
|
|
};
|
|
|
|
socket.OnMessage = message =>// 接收客户端发送过来的信息
|
|
{
|
|
|
|
};
|
|
});
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
|
|
log.WriteLogFile(e.ToString(), "recorderror");
|
|
}
|
|
|
|
}
|
|
|
|
public void CloasSocket() {
|
|
try
|
|
{
|
|
|
|
if (server != null)
|
|
{
|
|
server.Dispose();
|
|
server = null;
|
|
}
|
|
allSockets.RemoveRange(0, allSockets.Count);
|
|
allSockets.Clear();
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
log.WriteLogFile(e.Message, "ProgramServerError");
|
|
}
|
|
}
|
|
|
|
}
|
|
}
|
|
|