CTcpClient.cs
8.7 KB
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Threading;
namespace OnlineStore.Common
{
public class CTcpClient
{
// public static readonly ILog LOGGER = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public delegate void HandleMessage(string message);
private Socket m_clientSocket = null;
private byte[] m_receiveBuffer = new byte[1024];
private HandleMessage onReceived;
public int TimeOutTime = 0;
/// <summary>
/// 当前连接状态
/// </summary>
public bool IsConnected()
{
if (m_clientSocket == null)
{
return false;
}
if (m_clientSocket.Connected)
{
return true;
}
#region remarks
/********************************************************************************************
* 当Socket.Conneted为false时, 如果您需要确定连接的当前状态,请进行非阻塞、零字节的 Send 调用。
* 如果该调用成功返回或引发 WAEWOULDBLOCK 错误代码 (10035),则该套接字仍然处于连接状态;
* 否则,该套接字不再处于连接状态。
* Depending on http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socket.connected.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
********************************************************************************************/
#endregion
try
{
#region 过程
// This is how you can determine whether a socket is still connected.
bool connectState = true;
bool blockingState = m_clientSocket.Blocking;
try
{
byte[] tmp = new byte[1];
m_clientSocket.Blocking = false;
m_clientSocket.Send(tmp, 0, 0);
//Console.WriteLine("Connected!");
connectState = true; //若Send错误会跳去执行catch体,而不会执行其try体里其之后的代码
}
catch (SocketException e)
{
// 10035 == WSAEWOULDBLOCK
if (e.NativeErrorCode.Equals(10035))
{
connectState = true;
}
else
{
connectState = false;
}
}
finally
{
if (m_clientSocket != null && m_clientSocket.Connected)
{
m_clientSocket.Blocking = blockingState;
}
}
//Console.WriteLine("Connected: {0}", client.Connected);
return connectState;
#endregion
}
catch (Exception ex)
{
LogUtil.error( "出错啦" + ex.ToString());
return false;
}
}
/// <summary>
/// 连接服务器
/// </summary>
public bool connect(string serverIP, int serverPort, HandleMessage HandleMessage)
{
m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
if (TimeOutTime <= 0)
{
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(serverIP), serverPort);
m_clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
try
{
if (!m_clientSocket.Connected)
{
m_clientSocket.Connect(remoteEndPoint);
}
if (m_clientSocket.Connected)
{
m_clientSocket.BeginReceive(m_receiveBuffer, 0, m_receiveBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);
onReceived = HandleMessage;
LogUtil.info( "Connect to " + serverIP + ":" + serverPort + " success!");
return true;
}
else
{
LogUtil.info( "Connect to " + serverIP + ":" + serverPort + " fail!");
}
}
catch (Exception ex)
{
LogUtil.error( "Connect to " + serverIP + ":" + serverPort + " fail!" + ex.ToString(), 103);
//m_clientSocket = null;
}
}
else
{
m_clientSocket.ReceiveTimeout = TimeOutTime;
m_clientSocket.SendTimeout = TimeOutTime;
IAsyncResult connResult = m_clientSocket.BeginConnect(serverIP, serverPort, null, null);
connResult.AsyncWaitHandle.WaitOne(this.TimeOutTime, true); //等待2秒
if (!connResult.IsCompleted || (!m_clientSocket.Connected))
{
LogUtil.info( "Connect to " + serverIP + ":" + serverPort + " fail!");
m_clientSocket.Close();
//处理连接不成功的动作
return false;
}
else
{
//处理连接成功的动作
m_clientSocket.BeginReceive(m_receiveBuffer, 0, m_receiveBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);
onReceived = HandleMessage;
LogUtil.info( "Connect to " + serverIP + ":" + serverPort + " success!");
return true;
}
}
return false;
}
/// <summary>
/// 断开连接
/// </summary>
public void close()
{
try
{
if (m_clientSocket != null && m_clientSocket.Connected)
{
m_clientSocket.Shutdown(SocketShutdown.Both);
//Thread.Sleep(300);
//m_clientSocket.Disconnect(true);
//Thread.Sleep(300);
m_clientSocket.Close();
//m_clientSocket = null;
LogUtil.info( "Socket closed!");
}
else
{
LogUtil.error( "No socket is running!");
}
}
catch (Exception ex)
{
LogUtil.error( "close error :" + ex.ToString());
}
}
/// <summary>
/// 发送信息
/// </summary>
public void send(string strSendData)
{
byte[] sendBuffer = new byte[1024];
sendBuffer = Encoding.UTF8.GetBytes(strSendData);
if (m_clientSocket != null && m_clientSocket.Connected)
{
m_clientSocket.Send(sendBuffer);
LogUtil.debug( "Send >> " + strSendData);
}
}
/// <summary>
/// 发送信息
/// </summary>
public void sendLine(string strSendData)
{
if (strSendData.StartsWith("save"))
{
LogUtil.debug( "发送数据:" + strSendData);
}
else
{
LogUtil.info( "发送数据:" + strSendData);
}
strSendData = strSendData + "\r\n";
byte[] sendBuffer = new byte[1024];
sendBuffer = Encoding.UTF8.GetBytes(strSendData);
if (m_clientSocket != null && m_clientSocket.Connected)
{
m_clientSocket.Send(sendBuffer);
LogUtil.debug( "Send >> " + strSendData);
}
}
private void ReceiveCallBack(IAsyncResult ar)
{
try
{
if (m_clientSocket != null && m_clientSocket.Connected)
{
int REnd = m_clientSocket.EndReceive(ar);
string strReceiveData = Encoding.Default.GetString(m_receiveBuffer, 0, REnd);
onReceived(strReceiveData);
Thread.Sleep(100);
//LOGGER.Debug("m_clientSocket:" + m_clientSocket + "\n m_receiveBuffer" + m_receiveBuffer);
m_clientSocket.BeginReceive(m_receiveBuffer, 0, m_receiveBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);
}
}
catch (Exception ex)
{
LogUtil.error( "socket received error:" + ex.ToString(), 104);
}
}
}
}