/
TcpController.cs
130 lines (120 loc) · 3.19 KB
/
TcpController.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
namespace LanPlugin
{
public class TcpInfo
{
public TcpClient client { get; set; }
public NetworkStream stream { get; set; }
}
public enum TcpMode { None=0,Server, Client }
public class TcpController
{
LanPlugin _plugin;
ACTServer _server=null;
ACTClient _client=null;
public string Ip { get; set; }
public int Port { get; set; }
public TcpController(LanPlugin plugin)
{
_plugin = plugin;
}
bool _active=false;
public bool Active {
get { return _active; }
}
public event EventHandler ActiveUpdate;
public void OnActiveUpdate()
{
if (ActiveUpdate != null)
ActiveUpdate(this, EventArgs.Empty);
}
TcpMode _mode;
public TcpMode Mode {
get { return _mode; }
set
{
if (_active)
return;
if (_mode == value)
return;
_mode = value;
OnModeUpdate();
}
}
public event EventHandler ModeUpdate;
public void OnModeUpdate()
{
if (ModeUpdate != null)
ModeUpdate(this, EventArgs.Empty);
}
public void Start()
{
if (_active)
return;
_active = true;
OnActiveUpdate();
if (_mode == TcpMode.Server) {
_server = new ACTServer(_plugin);
_server.Close += OnClose;
_server.Start();
}
else if(_mode == TcpMode.Client) {
_client = new ACTClient(_plugin);
_client.Close += OnClose;
_client.Start();
}
}
public void Stop()
{
if (!_active)
return;
if (_mode == TcpMode.Server)
{
if(_server != null)
_server.Stop();
_server = null;
}
else if (_mode == TcpMode.Client)
{
if(_client != null)
_client.Stop();
_client = null;
}
}
private void OnClose(object sender, EventArgs e)
{
_active = false;
OnActiveUpdate();
}
public IPAddress GetIP()
{
IPAddress addr = null;
try
{
IPHostEntry iphe = Dns.GetHostEntry(this.Ip);
foreach (var i in iphe.AddressList)
{
if (i.AddressFamily == AddressFamily.InterNetwork)
{
addr = i;
break;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
if (addr == null)
{
addr = IPAddress.Any;
}
return addr;
}
}
}