RemoteClient.cs
6.4 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
using log4net;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
public class RemoteClient
{
public string GroupName;
public string Serveraddr;
WebSocket4Net.WebSocket webSocket;
readonly ILog LOGGER = LogManager.GetLogger("RollingLogFileAppender");
System.Timers.Timer timer;
public RemoteClient( string groupName, string serveraddr)
{
GroupName = groupName;
Serveraddr = serveraddr;
timer = new System.Timers.Timer(1000*10);
timer.Enabled = false;
timer.AutoReset = true;
timer.Elapsed += Timer_Elapsed;
webSocket = new WebSocket4Net.WebSocket(Serveraddr + GroupName);
LOGGER.Info("webSocket:" + serveraddr + GroupName);
webSocket.MessageReceived += WebSocket_MessageReceived;
webSocket.Closed += WebSocket_Closed;
webSocket.Opened += WebSocket_Opened;
//webSocket.AutoSendPingInterval = 2;
//webSocket.EnableAutoSendPing = true;
LOGGER.Info("webSocket open");
webSocket.Open();
timer.Start();
}
private void WebSocket_Opened(object sender, EventArgs e)
{
LOGGER.Info($"Remote:{GroupName} 连接成功");
LastState = webSocket.State;
}
private void WebSocket_Closed(object sender, EventArgs e)
{
if (LastState != webSocket.State)
{
LOGGER.Error($"Remote:{GroupName} 掉线了");
}
LastState = webSocket.State;
}
WebSocket4Net.WebSocketState LastState = WebSocket4Net.WebSocketState.None;
public bool IsOnline { get => webSocket.State == WebSocket4Net.WebSocketState.Open; }
int errstatuscounr = 0;
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
Debug.WriteLine("WebSocketState:"+ webSocket.State);
if (webSocket.State == WebSocket4Net.WebSocketState.Closed)
{
try
{
LOGGER.Info($"Remote:{GroupName} 重新连接");
webSocket.Open();
timeoutCount = 0;
errstatuscounr = 0;
}
catch { }
}
else if (webSocket.State == WebSocket4Net.WebSocketState.Connecting)
{
errstatuscounr++;
if (errstatuscounr > 5)
{
LOGGER.Error($"Remote:{GroupName} Connecting 超时");
try { webSocket.Close(); } catch { }
webSocket.Open();
errstatuscounr = 0;
}
}
else if (webSocket.State == WebSocket4Net.WebSocketState.Open)
{
RemoteLoad remoteLoad = new RemoteLoad();
remoteLoad.Seq = DateTime.Now.Ticks;
remoteLoad.Action = "Heartbeats";
remoteLoad.GroupName = GroupName;
SendAndWait(remoteLoad);
//webSocket.Send(JsonConvert.SerializeObject(remoteLoad));
}
}
volatile RemoteResult lastresult = RemoteResult.None;
private void WebSocket_MessageReceived(object sender, WebSocket4Net.MessageReceivedEventArgs e)
{
bool isok = false;
lastresult = RemoteResult.None;
RemoteLoad remoteLoad;
try
{
remoteLoad = JsonConvert.DeserializeObject<RemoteLoad>(e.Message);
}
catch
{
LOGGER.Error("Cant Deserialize remote command:" + e.Message);
return;
}
switch (remoteLoad.Action)
{
case "OK":
case "FAIL":
lastresult = remoteLoad.Action == "OK" ? RemoteResult.True : RemoteResult.False;
LOGGER.Info("Revice Command Callback:" + remoteLoad.GroupName + " - " + remoteLoad.Action + " ,Seq:" + remoteLoad.Seq);
return;
default:
if (actionlist.ContainsKey(remoteLoad.Action)) {
LOGGER.Info("Revice remote command:" + remoteLoad.Action +",Seq:"+ remoteLoad.Seq);
isok= actionlist[remoteLoad.Action].Invoke(remoteLoad.RequestLoadInfo);
}
else
LOGGER.Info("unknow remote command:" + remoteLoad.Action);
break;
}
SendResult(isok, remoteLoad.Seq);
}
Dictionary<string, Func<RequestLoadInfo, bool>> actionlist = new Dictionary<string, Func<RequestLoadInfo, bool>>();
public void AddAction(string actionName, Func<RequestLoadInfo, bool> action)
{
actionlist[actionName] = action;
}
int timeoutCount = 0;
RemoteResult WaitResult(int waittime=3000)
{
while (lastresult == RemoteResult.None && waittime > 0)
{
System.Threading.Thread.Sleep(50);
waittime = waittime - 50;
}
if (lastresult == RemoteResult.None)
{
LOGGER.Error("等待远程反馈超时");
timeoutCount++;
lastresult = RemoteResult.Timeout;
if (timeoutCount > 3)
{
LOGGER.Error("强制断开连接");
webSocket.Close();
timeoutCount = 0;
}
}
else {
timeoutCount = 0;
}
return lastresult;
}
/// <summary>
/// 发送并等待结果
/// </summary>
/// <param name="remoteLoad"></param>
/// <param name="waittime"></param>
/// <returns></returns>
public RemoteResult SendAndWait(RemoteLoad remoteLoad, int waittime= 3000) {
lock (webSocket) {
remoteLoad.Seq = DateTime.Now.Ticks;
remoteLoad.GroupName = GroupName;
if (remoteLoad.RequestLoadInfo != null)
{
if (string.IsNullOrEmpty(remoteLoad.RequestLoadInfo.DeviceGroupName))
remoteLoad.RequestLoadInfo.DeviceGroupName = GroupName;
}
lastresult = RemoteResult.None;
LOGGER.Info($"Send remote command: {GroupName} - " + remoteLoad.Action + $", seq:{remoteLoad.Seq}");
webSocket.Send(JsonConvert.SerializeObject(remoteLoad));
return WaitResult(waittime);
}
}
void SendResult(bool result,long Seq)
{
RemoteLoad remoteLoad = new RemoteLoad();
remoteLoad.Seq = Seq;
remoteLoad.Action = result ? "OK" : "FAIL";
remoteLoad.GroupName = GroupName;
webSocket.Send(JsonConvert.SerializeObject(remoteLoad));
}
}