-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathTCPConn.cs
136 lines (121 loc) · 3.54 KB
/
TCPConn.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
131
132
133
134
135
136
namespace BotwTrainer
{
using System;
using System.IO;
using System.Net.Sockets;
using System.Windows;
public class TcpConn
{
private TcpClient client;
private NetworkStream stream;
public TcpConn(string host, int port)
{
this.Host = host;
this.Port = port;
this.client = null;
this.stream = null;
}
private string Host { get; set; }
private int Port { get; set; }
public void Connect()
{
try
{
this.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
this.client = new TcpClient { NoDelay = true };
var ar = this.client.BeginConnect(this.Host, this.Port, null, null);
var wh = ar.AsyncWaitHandle;
try
{
if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false))
{
this.client.Close();
throw new IOException("Connection timeout.", new TimeoutException());
}
this.client.EndConnect(ar);
}
finally
{
wh.Close();
}
this.stream = this.client.GetStream();
this.stream.ReadTimeout = 10000;
this.stream.WriteTimeout = 10000;
}
public void Close()
{
try
{
if (this.client == null)
{
return;
throw new IOException("Not connected.", new NullReferenceException());
}
this.client.Close();
}
finally
{
this.client = null;
}
}
public void Read(byte[] buffer, uint nobytes, ref uint bytesRead)
{
try
{
var offset = 0;
if (this.stream == null)
{
throw new IOException("Not connected.", new NullReferenceException());
}
bytesRead = 0;
while (nobytes > 0)
{
var read = this.stream.Read(buffer, offset, (int)nobytes);
if (read >= 0)
{
bytesRead += (uint)read;
offset += read;
nobytes -= (uint)read;
}
else
{
break;
}
}
}
catch (ObjectDisposedException e)
{
throw new IOException("Connection closed.", e);
}
}
public void Write(byte[] buffer, int nobytes, ref uint bytesWritten)
{
try
{
if (this.stream == null)
{
throw new IOException("Not connected.", new NullReferenceException());
}
this.stream.Write(buffer, 0, nobytes);
if (nobytes >= 0)
{
bytesWritten = (uint)nobytes;
}
else
{
bytesWritten = 0;
}
this.stream.Flush();
}
catch (ObjectDisposedException e)
{
throw new IOException("Connection closed.", e);
}
}
}
}