aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Region/ScriptEngine/Common/TRPC/TCPSocket.cs
diff options
context:
space:
mode:
Diffstat (limited to 'OpenSim/Region/ScriptEngine/Common/TRPC/TCPSocket.cs')
-rw-r--r--OpenSim/Region/ScriptEngine/Common/TRPC/TCPSocket.cs86
1 files changed, 86 insertions, 0 deletions
diff --git a/OpenSim/Region/ScriptEngine/Common/TRPC/TCPSocket.cs b/OpenSim/Region/ScriptEngine/Common/TRPC/TCPSocket.cs
new file mode 100644
index 0000000..1079846
--- /dev/null
+++ b/OpenSim/Region/ScriptEngine/Common/TRPC/TCPSocket.cs
@@ -0,0 +1,86 @@
1using System;
2using System.Net.Sockets;
3
4namespace OpenSim.Region.ScriptEngine.Common.TRPC
5{
6 public class TCPSocket
7 {
8
9 public readonly Socket Client;
10 public readonly int ID;
11
12 public delegate void DataReceivedDelegate(int ID, byte[] data, int offset, int length);
13 public delegate void DataSentDelegate(int ID, int length);
14 public delegate void CloseDelegate(int ID);
15 public event DataReceivedDelegate DataReceived;
16 public event DataSentDelegate DataSent;
17 public event CloseDelegate Close;
18
19 private byte[] RecvQueue = new byte[4096];
20 private int RecvQueueSize = 4096;
21
22 public TCPSocket(int id, Socket client)
23 {
24 ID = id;
25 Client = client;
26 }
27 public void Start()
28 {
29 // Start listening
30 BeginReceive();
31 }
32
33 private void BeginReceive()
34 {
35 Client.BeginReceive(RecvQueue, 0, RecvQueueSize, SocketFlags.None, new AsyncCallback(asyncDataReceived), Client);
36 }
37
38 /// <summary>
39 /// Callback for successful receive (or connection close)
40 /// </summary>
41 /// <param name="ar"></param>
42 private void asyncDataReceived(IAsyncResult ar)
43 {
44 Socket client = (Socket)ar.AsyncState;
45 int recv = client.EndReceive(ar);
46
47 // Is connection closed?
48 if (recv == 0)
49 {
50 client.Close();
51 Close(ID);
52 return;
53 }
54
55 // Call receive event
56 DataReceived(ID, RecvQueue, 0, recv);
57
58 // Start new receive
59 BeginReceive();
60
61 }
62
63
64 public void Send(int clientID, byte[] data, int offset, int len)
65 {
66 Client.BeginSend(data, offset, len, SocketFlags.None, new AsyncCallback(asyncDataSent), Client);
67 }
68
69 /// <summary>
70 /// Callback for successful send
71 /// </summary>
72 /// <param name="ar"></param>
73 void asyncDataSent(IAsyncResult ar)
74 {
75 Socket client = (Socket)ar.AsyncState;
76 int sent = client.EndSend(ar);
77 DataSent(ID, sent);
78 }
79
80 public void Disconnect()
81 {
82 Client.Close();
83 Close(ID);
84 }
85 }
86} \ No newline at end of file