flysun027

有思想的博客
随笔 - 32, 文章 - 0, 评论 - 22, 阅读 - 74193

导航

< 2025年2月 >
26 27 28 29 30 31 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 1
2 3 4 5 6 7 8

C# socket 连接超时代码实现

Posted on   flysun027  阅读(1054)  评论(0编辑  收藏  举报

在写 C# socket 的时候发现 socket 连接无法设置超时时间,需要15s才能超时返回。百度一下发现也没有实现的比较好的代码。

因此,才有了下面这段 socket 连接超时的代码,这段代码已经应用到实际的项目中,并且运行稳定。

如果你有更好的实现方案可以给我留言。

 

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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
class Socket2 : IComunication
{
    static IPEndPoint ipe;
 
    static byte[] sendBytes = new byte[1400];
    static byte[] recBytes = new byte[1400];
 
    volatile static Socket socket = null;
 
    static System.Threading.Timer readTimer = null;
    static int readOverTime;
    static bool ReadOK;
    static System.Threading.Timer connectTimer = null;
    static int connectOverTime;
 
    public Socket2()
    {
        readTimer = new System.Threading.Timer(OnReadTimeUp, null, Timeout.Infinite, Timeout.Infinite);
 
        object obj = Global.Config.Read("ReadOverTime");
        if (obj == null || !int.TryParse(obj.ToString(), out readOverTime))
        {
            readOverTime = 3000;
        }
 
        obj = Global.Config.Read("ConnectOverTime");
        if (obj == null || !int.TryParse(obj.ToString(), out connectOverTime))
        {
            connectOverTime = 3000;
        }
    }
 
 
    private static void OnConnectTimeUp(object obj)
    {
        StateObject stateObject = (StateObject)obj;
        lock (connectTimer)
        {
            if (stateObject.socket != null)
            {
                stateObject.socket.Close();
                stateObject.socket = null;
                socket = null;
            }
        }
    }
 
    private static void OnReadTimeUp(object obj)
    {
        ReadOK = false;
        socket.Close();
    }
 
    public bool Start()
    {
        try
        {
            if (socket == null)
            {
                string host = Global.Config.Read("DriverIP").ToString();
                int port = Convert.ToInt32(Global.Config.Read("DriverPort"));
                IPAddress ip = IPAddress.Parse(host);
                ipe = new IPEndPoint(ip, port);
 
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 
                socket.DontFragment = false;
                socket.ExclusiveAddressUse = true;
                socket.UseOnlyOverlappedIO = false;
                socket.SendBufferSize = 1500;
                socket.ReceiveBufferSize = 1500;
                socket.ReceiveTimeout = readOverTime;
                socket.SendTimeout = readOverTime;
                // 设置连接超时计时器
                StateObject so = new StateObject();
                so.socket = socket;
 
                //socket.Connect(ipe);
                connectTimer = new System.Threading.Timer(OnConnectTimeUp, so, Timeout.Infinite, Timeout.Infinite);
                connectTimer.Change(connectOverTime, Timeout.Infinite);
                socket.BeginConnect(ipe, new AsyncCallback(ConnectCallback), so);
                autoEventConnect.WaitOne();
            }
            return true;
        }
        catch (SocketException e)
        {
            Global.log.Debug(e);
            socket.Close();
            socket = null;
            return false;
        }
        catch (Exception e)
        {
            if (socket != null)
            {
                socket.Close();
            }
            socket = null;
            return false;
        }
    }
 
    AutoResetEvent autoEventConnect = new AutoResetEvent(false);
 
    private void ConnectCallback(IAsyncResult ar)
    {
        // Retrieve the socket from the state object.
        StateObject stateObject = (StateObject)ar.AsyncState;
        lock (connectTimer)
        {
            try
            {
                if (stateObject.socket != null)
                {
                    // Complete the connection.
                    stateObject.socket.EndConnect(ar);
 
                    connectTimer.Change(Timeout.Infinite, Timeout.Infinite);
                    connectTimer.Dispose();
                }
            }
            catch (Exception e)
            {
                if (stateObject.socket != null)
                {
                    stateObject.socket.Close();
                }
                stateObject.socket = null;
                stateObject.reciveBuffer = null;
                stateObject.sendBuffer = null;
                stateObject = null;
            }
        }
        autoEventConnect.Set();
    }
 
 
    public bool Stop()
    {
        if (socket != null)
        {
            socket.Close();
        }
        socket = null;
        return true;
    }
 
    public bool Write()
    {
        try
        {
            if (socket != null)
            {
                buildSendBytes();
                socket.NoDelay = true;
                int n = socket.Send(sendBytes, sendBytes.Length , SocketFlags.None);
                if (n != sendBytes.Length)
                {
                    Global.log.Debug("send error 需要发送的字节数 " + "实际发送的字节数" + sendBytes.Length + ":" +n);
                }
                return true;
            }
            else
            {
                return false;
            }
        }
        catch (Exception e)
        {
            Global.log.Debug("Error Send");
            Global.log.Debug(e);
            if (socket != null)
            {
                socket.Close();
                socket = null;
            }
            return false;
        }
    }
 
    public bool Read()
    {
        try
        {
            if (socket != null)
            {
                StateObject so = new StateObject();
 
                so.socket = socket;
                so.reciveBuffer = recBytes;
                // 设置读超时计时器
                readTimer.Change(readOverTime, Timeout.Infinite);
 
                socket.BeginReceive(recBytes, 0, recBytes.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), so);
                // 接受完成
                autoEvent.WaitOne();
                readTimer.Change(Timeout.Infinite, Timeout.Infinite);
                buildRecBytes();
                // 需要添加读超时返回 false
                if (ReadOK == true)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        catch (Exception e)
        {
            Global.log.Debug(e);
            return false;
        }
    }
 
    AutoResetEvent autoEvent = new AutoResetEvent(false);
 
    public class StateObject
    {
        public Socket socket = null;
        public byte[] reciveBuffer = null;
        public byte[] sendBuffer = null;
    }
 
    volatile int bytesRecieved = 0;
 
    public void ReceiveCallback(IAsyncResult ar)
    {
        StateObject state = null;
        try
        {
            // Retrieve the state object and the client socket
            // from the asynchronous state object.
            state = (StateObject)ar.AsyncState;
 
            // Read data from the remote device.
            int bytesRead = state.socket.EndReceive(ar);
            if (bytesRead > 1400)
            {
                Global.log.Debug("bytesRead > 1400 :" + bytesRead);
            }
            if (bytesRead > 0)
            {
                bytesRecieved += bytesRead;
                if (bytesRecieved < recBytes.Length)
                {
                    state.socket.BeginReceive(state.reciveBuffer, bytesRecieved, state.reciveBuffer.Length - bytesRecieved, SocketFlags.None, new AsyncCallback(ReceiveCallback), state);
                }
                if (bytesRecieved == recBytes.Length)
                {
                    bytesRecieved = 0;
                    ReadOK = true;
                    autoEvent.Set();
                }
            }
            else
            {
                state.socket.Close();
                state.socket = null;
                socket = null;
                state.reciveBuffer = null;
                state.sendBuffer = null;
                state = null;
                ReadOK = false;
                autoEvent.Set();
            }
 
        }
        catch (Exception e)
        {
            Global.log.Debug("Error Recieve");
            Global.log.Debug(e);
            if (state.socket != null)
            {
                state.socket.Close();
                state.socket = null;
                socket = null;
            }
 
            state.reciveBuffer = null;
            state.sendBuffer = null;
            state = null;
            ReadOK = false;
            autoEvent.Set();
        }
    }
 
    public bool ReadArray()
    {
        throw new NotImplementedException();
    }
 
    public bool WriteArray()
    {
        throw new NotImplementedException();
    }
}

 

编辑推荐:
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
阅读排行:
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
点击右上角即可分享
微信分享提示