-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathSocketPump.cs
100 lines (95 loc) · 2.05 KB
/
SocketPump.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace SocksTun
{
public static class SocketPump
{
public static void Pump(Socket s1, Socket s2)
{
var wh = new ManualResetEvent(false);
var p1 = new SinglePump(s1, s2, wh);
var p2 = new SinglePump(s2, s1, wh);
p1.Pump();
p2.Pump();
while (s1.Connected && s2.Connected && !p1.finished && !p2.finished)
{
wh.WaitOne(10000);
}
}
class SinglePump
{
const int bufferSize = 10000;
private readonly Socket s1;
private readonly Socket s2;
private readonly EventWaitHandle finishedEvent;
private readonly byte[] buf = new byte[bufferSize];
public bool finished { get; private set; }
public SinglePump(Socket s1, Socket s2, EventWaitHandle finishedEvent)
{
this.s1 = s1;
this.s2 = s2;
this.finishedEvent = finishedEvent;
}
public void Pump()
{
try
{
if (!s1.Connected || !s2.Connected)
{
finished = true;
finishedEvent.Set();
return;
}
s1.BeginReceive(buf, 0, bufferSize, SocketFlags.None, ReceiveCallback, null);
}
catch (ObjectDisposedException)
{
finished = true;
finishedEvent.Set();
}
catch (SocketException)
{
finished = true;
finishedEvent.Set();
}
}
private void ReceiveCallback(IAsyncResult ar)
{
try
{
if (!s1.Connected || !s2.Connected)
{
finished = true;
finishedEvent.Set();
return;
}
var bytesReceived = s1.EndReceive(ar);
if (bytesReceived > 0)
{
s2.Send(buf, 0, bytesReceived, SocketFlags.None);
Pump();
}
else
{
finished = true;
finishedEvent.Set();
}
}
catch (ObjectDisposedException)
{
finished = true;
finishedEvent.Set();
}
catch (SocketException)
{
finished = true;
finishedEvent.Set();
}
}
}
}
}