forked from nscript-site/NScript.AndroidBot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathController.cs
More file actions
95 lines (83 loc) · 2.56 KB
/
Controller.cs
File metadata and controls
95 lines (83 loc) · 2.56 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
namespace NScript.AndroidBot
{
public class Controller
{
public Socket ControlSocket { get; private set; }
public Queue<ControlMsg> queue { get; set; } = new Queue<ControlMsg>();
private Object syncRoot = new object();
public bool Stopped { get; set; }
private bool ForceRunningTaskExit { get; set; }
public bool Push(ControlMsg msg)
{
if (msg == null) return false;
lock(syncRoot)
queue.Enqueue(msg);
return true;
}
private Task task;
private byte[] serialized_msg = new byte[Setting.CONTROL_MSG_MAX_SIZE];
public unsafe bool ProcessMsg(ControlMsg msg)
{
if(msg is WaitMsg) {
int miniSeconds = ((WaitMsg)msg).MiniSeconds;
System.Threading.Thread.Sleep(miniSeconds);
return true;
}
fixed(Byte* pBuff = serialized_msg)
{
int len = msg.Serialize(pBuff);
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(pBuff, len);
int sendLen = NetUtils.SendAll(ControlSocket, span);
return sendLen == len;
}
}
public void Bind(Socket socket)
{
if(task != null)
{
ForceRunningTaskExit = true;
queue.Clear();
task.Wait();
}
ForceRunningTaskExit = false;
this.ControlSocket = socket;
task = new Task(RunCore);
task.Start();
}
private void RunCore()
{
while(true)
{
if (ForceRunningTaskExit == true) break;
if(Stopped == true || queue.Count == 0)
{
System.Threading.Thread.Sleep(200);
continue;
}
ControlMsg msg = null;
lock(syncRoot)
{
if(queue.Count > 0)
msg = queue.Dequeue();
}
if(msg != null)
{
try
{
ProcessMsg(msg);
}
catch(SocketException ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
}
}