forked from ctacke/extensions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TcpSocketServer.cs
109 lines (95 loc) · 3.06 KB
/
TcpSocketServer.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
#if !PCL
using OpenNETCF;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace System.Net.Sockets
{
public class TcpSocketServer
{
public event EventHandler<GenericEventArgs<byte[]>> DataReceived;
public event EventHandler ClientConnected;
private Socket m_listener;
private Socket m_server;
private int m_port;
private byte[] m_buffer;
public TcpSocketServer(int port)
{
m_port = port;
m_buffer = new byte[4096];
}
public bool IsConnected
{
get
{
if (m_server == null) return false;
return m_server.Connected;
}
}
public IPEndPoint ClientAddress
{
get
{
if (m_server == null) return null;
if (!m_server.Connected) return null;
return (IPEndPoint)m_server.RemoteEndPoint;
}
}
public void Start()
{
m_listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var ep = new IPEndPoint(IPAddress.Any, m_port);
m_listener.Bind(ep);
m_listener.Listen(100);
m_listener.BeginAccept(AcceptCallback, null);
}
private void AcceptCallback(IAsyncResult ar)
{
m_server = m_listener.EndAccept(ar);
m_server.BeginReceive(m_buffer, 0, m_buffer.Length, SocketFlags.None, ReceiveCallback, null);
ClientConnected.Fire(this, EventArgs.Empty);
}
private void ReceiveCallback(IAsyncResult ar)
{
SocketError error;
var length = m_server.EndReceive(ar, out error);
switch (error)
{
case SocketError.Success:
try
{
var buffer = new byte[length];
Buffer.BlockCopy(m_buffer, 0, buffer, 0, buffer.Length);
DataReceived.Fire(this, new GenericEventArgs<byte[]>(buffer));
}
finally
{
m_server.BeginReceive(m_buffer, 0, m_buffer.Length, SocketFlags.None, ReceiveCallback, null);
}
break;
case SocketError.ConnectionReset:
// client disconnected and reconnected? // re-start?
default:
try
{
m_server.Close();
m_listener.Close();
Start();
}
catch(Exception ex)
{
Debug.WriteLine(ex.Message);
if (Debugger.IsAttached) Debugger.Break();
}
break;
}
}
public int Send(byte[] data)
{
return m_server.Send(data);
}
}
}
#endif