Unity3d +vs2012 多线程.多并发网络解决方案(C#)

来源:互联网 发布:苹果越狱音乐软件 编辑:程序博客网 时间:2024/05/23 01:18
此方案和结构在多线程多并发大吞吐下有绝对的效率优势
以下是服务端 vs2012 C#
复制代码
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
usingSystem;
usingSystem.IO;
usingSystem.ComponentModel;
usingSystem.Collections;
usingSystem.Collections.Generic;
usingSystem.Diagnostics;
usingSystem.Net;
usingSystem.Net.Sockets;
usingSystem.Threading;
usingTools;
usingGameDates;
      
namespaceTestServer
{
    /// <summary>
    /// MyTcpIpClient 提供在Net TCP_IP 协议上基于消息的服务端 
    /// </summary>
    publicclass MyTcpIpServer : System.ComponentModel.Component
    {
        privateint bufferSize=2048;
        privatestring tcpIpServerIP="127.0.0.1";
        privateint tcpIpServerPort=11000;
        privateSocket listener=null;
        privateManualResetEvent allDone = newManualResetEvent(false);
        privateManualResetEvent sendDone = newManualResetEvent(false);
        privateThread thread=null;
      
        publicstatic List<StateObject> StateList =new List<StateObject>();
              
        privatevoid StartListening() 
        {
            try
            {
                listener =new Socket(AddressFamily.InterNetwork,
                    SocketType.Stream, ProtocolType.Tcp);
                          
                IPAddress ipAddress;
                if(tcpIpServerIP.Trim()=="")
                {
                    ipAddress=IPAddress.Any;    
                }
                else
                {
                    ipAddress=IPAddress.Parse(tcpIpServerIP);
                }
                IPEndPoint localEndPoint =new IPEndPoint(ipAddress, tcpIpServerPort);
                      
                listener.Bind(localEndPoint);
                listener.Listen(10);
                while(true
                {
                    allDone.Reset();
                    listener.BeginAccept(newAsyncCallback(AcceptCallback),listener);
                    allDone.WaitOne();
                }
            
            catch(Exception e) 
            {
                OnErrorServerEvent(newErrorServerEventArgs(e,listener));    
            }
        }
              
        privatevoid ReadCallback(IAsyncResult ar) 
        {
            Socket handler=null;
            try
            {
                lock(ar)
                {
                    StateObject state = (StateObject) ar.AsyncState;
                    handler = state.workSocket;
                          
                    intbytesRead = handler.EndReceive(ar);
                          
                    if(bytesRead > 0) 
                    {
                        intReadPiont=0;    
                        while(ReadPiont<bytesRead)
                        {    
                            if(state.Cortrol==0 && ReadPiont<bytesRead)
                            {
                                longbi1=state.buffer[ReadPiont];
                                bi1=(bi1<<24)&0xff000000;
                                state.packSize=bi1;
                                ReadPiont++;
                                state.Cortrol=1;
                            }
                              
                            if(state.Cortrol==1 && ReadPiont<bytesRead)
                            {
                                longbi1=state.buffer[ReadPiont];
                                bi1=(bi1<<16)&0x00ff0000;
                                state.packSize=state.packSize+bi1;
                                ReadPiont++;
                                state.Cortrol=2;
                            }
                              
                            if(state.Cortrol==2 && ReadPiont<bytesRead)
                            {
                                longbi1=state.buffer[ReadPiont];
                                bi1=(bi1<<8)&0x0000ff00;
                                state.packSize=state.packSize+bi1;
                                ReadPiont++;
                                state.Cortrol=3;
                            }
                                  
                            if(state.Cortrol==3 && ReadPiont<bytesRead)
                            {
                                longbi1=state.buffer[ReadPiont];
                                bi1=bi1&0xff;
                                state.packSize=state.packSize+bi1-4;
                                ReadPiont++;
                                state.Cortrol=4;
                            }
                                  
                            if(state.Cortrol==4 && ReadPiont<bytesRead)
                            {
                                longbi1=state.buffer[ReadPiont];
                                bi1=(bi1<<24)&0xff000000;
                                state.residualSize=bi1;
                                ReadPiont++;
                                state.Cortrol=5;
                                state.packSize-=1;
                            }
                                  
                            if(state.Cortrol==5 && ReadPiont<bytesRead)
                            {
                                longbi1=state.buffer[ReadPiont];
                                bi1=(bi1<<16)&0x00ff0000;
                                state.residualSize=state.residualSize+bi1;
                                ReadPiont++;
                                state.Cortrol=6;
                                state.packSize-=1;
                            }
                                  
                            if(state.Cortrol==6 && ReadPiont<bytesRead)
                            {
                                longbi1=state.buffer[ReadPiont];
                                bi1=(bi1<<8)&0x0000ff00;
                                state.residualSize=state.residualSize+bi1;
                                ReadPiont++;
                                state.Cortrol=7;
                                state.packSize-=1;
                            }
                            if(state.Cortrol==7 && ReadPiont<bytesRead)
                            {
                                longbi1=state.buffer[ReadPiont];
                                bi1=bi1&0xff;
                                state.residualSize=state.residualSize+bi1;
                                state.Datastream.SetLength(0);
                                state.Datastream.Position=0;
                                      
                                ReadPiont++;
                                state.Cortrol=8;
                                state.packSize-=1;
                            }
                                  
                            if(state.Cortrol==8 && ReadPiont<bytesRead)
                            {
                                intbi1=bytesRead-ReadPiont;
                                intbi2=(int)(state.residualSize-state.Datastream.Length);
                                if(bi1>=bi2)
                                {
                                    state.Datastream.Write(state.buffer,ReadPiont,bi2);
                                    ReadPiont+=bi2;
                                    OnInceptServerEvent(newInceptServerEventArgs(state.Datastream,state.workSocket,this));
                                    state.Cortrol=9;
                                    state.packSize-=bi2;
                                          
                                          
                                }
                                else
                                {
                                    state.Datastream.Write(state.buffer,ReadPiont,bi1);
                                    ReadPiont+=bi1;
                                    state.packSize-=bi1;
                                }
                            }
                            if(state.Cortrol==9 && ReadPiont<bytesRead)
                            {
                                intbi1=bytesRead-ReadPiont;
                                if(bi1<state.packSize)
                                {
                                    state.packSize=state.packSize-bi1;
                                    ReadPiont+=bi1;
                                }    
                                else
                                {
                                    state.Cortrol=0;
                                    ReadPiont+=(int)state.packSize;
                                }
                            }
                        }
                        if(handler.Connected==true)
                        {
                            //异步读取数据流
                            handler.BeginReceive(state.buffer,0,bufferSize,0,newAsyncCallback(ReadCallback), state);
                            Console.WriteLine("接收字节长度【{0}】", state.buffer.Length);
                            //获取有效数据长度
                            longsize = state.residualSize;
      
                            //解析数据....
                        }
                    }
                    else
                    {
                        handler.Shutdown(SocketShutdown.Both);
                        handler.Close();
                        //throw(new Exception("读入的数据小于1bit"));
                    }
                }
            }
            catch(Exception e) 
            {
                OnErrorServerEvent(newErrorServerEventArgs(e,handler));
                      
            }
        }
              
        privatevoid SendCallback(IAsyncResult ar) 
        {
            Socket client = (Socket) ar.AsyncState;
            try
            {
                intbytesSent = client.EndSend(ar);
            
            catch(Exception e) 
            {
                OnErrorServerEvent(newErrorServerEventArgs(e,client));
            }
            finally
            {
                sendDone.Set();
            }
        }
              
        privatevoid AcceptCallback(IAsyncResult ar) 
        {
            Socket handler=null;
            try
            {
                Socket listener = (Socket) ar.AsyncState;
                handler= listener.EndAccept(ar);
                StateObject state =new StateObject(bufferSize,handler);
                state.workSocket = handler;
                IPEndPoint msg = (IPEndPoint)state.workSocket.RemoteEndPoint;
                state.ip = msg.Address.ToString();
                state.prot = msg.Port;
                StateList.Add(state);
                Console.WriteLine("连接数[{0}],{1}", StateList.Count, state.workSocket.RemoteEndPoint);
                handler.BeginReceive(state.buffer,0,bufferSize,0,newAsyncCallback(ReadCallback), state);
            }
            catch(Exception e) 
            {
                OnErrorServerEvent(newErrorServerEventArgs(e,handler));
            }
            finally
            {
                allDone.Set();
            }
        }
      
              
        /// <summary>
        /// 析构
        /// </summary>
        /// <param name="disposing">不知道</param>
        protectedoverride void Dispose(bool disposing)
        {
            Abort();
        }
              
        /// <summary>
        /// 引发接收事件
        /// </summary>
        /// <param name="e">数据</param>
        protectedvirtual void OnInceptServerEvent(InceptServerEventArgs e)
        {
            if(InceptServer != null
            {
                InceptServer(this, e);
            }
        }
        /// <summary>
        /// 引发错误事件
        /// </summary>
        /// <param name="e">数据</param>
        protectedvirtual void OnErrorServerEvent(ErrorServerEventArgs e)
        {
            if(ErrorServer != null
            {
                ErrorServer(this, e); 
            }
        }
              
        /// <summary>
        /// 开始监听访问
        /// </summary>
        publicvoid Listening()
        {
            //StartListening();
            thread=newThread(new ThreadStart(StartListening));
            thread.Name="MyTcpIpServer.Listening";
            thread.Start();
        }
        /// <summary>
        /// 异常中止服务
        /// </summary>
        publicvoid Abort()
        {
            if(thread!=null)
            {
                thread.Abort();
                listener.Close();
            }
        }
              
        /// <summary>
        ///构造 
        /// </summary>
        /// <param name="container">父控件</param>
        publicMyTcpIpServer(System.ComponentModel.IContainer container)
        {
            container.Add(this);
            //InitializeComponent();
      
            //
            // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
            //
        }
      
        /// <summary>
        /// 构造
        /// </summary>
        publicMyTcpIpServer()
        {
            StartListening();
        }
      
      
      
      
      
        /// <summary>
        /// 要连接的服务器IP地址
        /// </summary>
        publicstring TcpIpServerIP
        {
            get
            {
                returntcpIpServerIP;
            }
            set
            {
                tcpIpServerIP=value;
            }
        }
      
        /// <summary>
        /// 要连接的服务器所使用的端口
        /// </summary>
        publicint TcpIpServerPort
        {
            get
            {
                returntcpIpServerPort;
            }
            set
            {
                tcpIpServerPort=value;
            }
        }
      
        /// <summary>
        /// 缓冲器大小
        /// </summary>
        publicint BufferSize
        {
            get
            {
                returnbufferSize;
            }
            set
            {
                bufferSize=value;
            }
        }
              
        /// <summary>
        /// 连接的活动状态
        /// </summary>
        publicbool Activ
        {
            get
            {
                returnlistener.Connected;
            }
            //set
            //{
            //    activ=value;
            //}
        }
      
        /// <summary>
        /// 发送一个流数据
        /// </summary>
        publicvoid Send(Socket ClientSocket,Stream Astream)
        {
            try
            {
                if(ClientSocket.Connected==false)
                {
                    throw(newException("没有连接客户端不可以发送信息!"));
                }
                Astream.Position=0;
                byte[] byteData=newbyte[bufferSize];
                intbi1=(int)((Astream.Length+8)/bufferSize);
                intbi2=(int)Astream.Length;
                if(((Astream.Length+8)%bufferSize)>0)
                {
                    bi1=bi1+1;
                }
                bi1=bi1*bufferSize;
                      
                byteData[0]=System.Convert.ToByte(bi1>>24);
                byteData[1]=System.Convert.ToByte((bi1&0x00ff0000)>>16);
                byteData[2]=System.Convert.ToByte((bi1&0x0000ff00)>>8);
                byteData[3]=System.Convert.ToByte((bi1&0x000000ff));
                      
                byteData[4]=System.Convert.ToByte(bi2>>24);
                byteData[5]=System.Convert.ToByte((bi2&0x00ff0000)>>16);
                byteData[6]=System.Convert.ToByte((bi2&0x0000ff00)>>8);
                byteData[7]=System.Convert.ToByte((bi2&0x000000ff));
                      
                intn = Astream.Read(byteData, 8, byteData.Length-8);
                      
                while(n>0) 
                {
                    ClientSocket.BeginSend(byteData, 0, byteData.Length, 0,   new AsyncCallback(SendCallback), ClientSocket);
                    sendDone.WaitOne();
                    byteData=newbyte[bufferSize];
                    n = Astream.Read(byteData,0,byteData.Length);
                }
            
            catch(Exception e) 
            {
                OnErrorServerEvent(newErrorServerEventArgs(e,ClientSocket));
            }
        }
              
        /// <summary>
        /// 接收到数据事件
        /// </summary>
        publicevent InceptServerEvent InceptServer;
        /// <summary>
        /// 发生错误事件
        /// </summary>
        publicevent ErrorServerEvent ErrorServer;
    }
    /// <summary>
    /// 状态对象
    /// </summary>
    publicclass StateObject 
    {
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="bufferSize">缓存</param>
        /// <param name="WorkSocket">工作的插座</param>
        publicStateObject(int bufferSize,Socket WorkSocket)
        {
            buffer =new byte[bufferSize];
            workSocket=WorkSocket;
        }
        /// <summary>
        /// 缓存
        /// </summary>
        publicbyte[] buffer = null;
        /// <summary>
        /// 工作插座
        /// </summary>
        publicSocket workSocket = null;              
        /// <summary>
        /// 数据流
        /// </summary>
        publicStream Datastream=newMemoryStream();
        /// <summary>
        /// 剩余大小
        /// </summary>
        publiclong residualSize=0;
        /// <summary>
        /// 数据包大小
        /// </summary>
        publiclong packSize=0;
        /// <summary>
        /// 计数器
        /// </summary>
        publicint Cortrol=0;
      
        /// <summary>
        /// 客户端端口
        /// </summary>
        publicint prot;
      
        /// <summary>
        /// 客户端ip地址
        /// </summary>
        publicstring ip;
    }
          
    /// <summary>
    /// 接收事件
    /// </summary>
    publicclass InceptServerEventArgs : EventArgs 
    {  
        privatereadonly Stream datastream;
        privatereadonly Socket serverSocket;
        privatereadonly MyTcpIpServer tcpIpServer;
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="Astream">数据</param>
        /// <param name="ServerSocket">工作插座</param>
        /// <param name="TcpIpServer">提供服务的TCP/IP对象</param>
        publicInceptServerEventArgs(Stream Astream,Socket ServerSocket,MyTcpIpServer TcpIpServer) 
        {
            datastream=Astream;
            serverSocket=ServerSocket;
            tcpIpServer=TcpIpServer;
        }
    /// <summary>
    /// 数据
    /// </summary>
        publicStream Astream
        {     
            get{ return datastream;}      
        }
        /// <summary>
        /// 工作插座
        /// </summary>
        publicSocket ServerSocket
        {     
            get{ return serverSocket;}      
        }
        /// <summary>
        /// 提供TCP/IP服务的服务器对象.
        /// </summary>
        publicMyTcpIpServer TcpIpServer
        {     
            get{ return tcpIpServer;}      
        }
    }
    /// <summary>
    /// 接收数据委托
    /// </summary>
  publicdelegate void InceptServerEvent(object sender, InceptServerEventArgs e);
    /// <summary>
    /// 错误事件委托
    /// </summary>
    publicclass ErrorServerEventArgs : EventArgs 
    {  
        privatereadonly Exception error;
        privatereadonly Socket serverSocket;
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="Error">数据</param>
        /// <param name="ServerSocket">问题插座</param>
        publicErrorServerEventArgs(Exception Error,Socket ServerSocket) 
        {
            error=Error;
            serverSocket=ServerSocket;
        }
    /// <summary>
    /// 数据
    /// </summary>
        publicException Error
        {     
            get{ return error;}      
        }
        /// <summary>
        /// 问题插座
        /// </summary>
        publicSocket ServerSocket
        {     
            get{ return serverSocket;}      
        }
    }
    /// <summary>
    ///错误事件委托 
    /// </summary>
  publicdelegate void ErrorServerEvent(object sender, ErrorServerEventArgs e);
}

 
客户端部分 Unity3d 4.1.0 C#
复制代码
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
550
551
///MainClass.cs
      
usingUnityEngine;
usingclinet;
publicclass Index : MonoBehaviour 
{
    voidAwake()
     {
        newMyTcpIpClient();
     
}
      
      
///GameClient.cs
      
usingSystem;
usingSystem.IO;
usingSystem.ComponentModel;
usingSystem.Collections;
usingSystem.Diagnostics;
usingSystem.Net;
usingSystem.Net.Sockets;
usingSystem.Threading;
usingTools;
usingGameDates;
      
namespaceclinet
{
    /// <summary>
    /// MyTcpIpClient 提供在Net TCP_IP 协议上基于消息的客户端 
    /// </summary>
    publicclass MyTcpIpClient : System.ComponentModel.Component
    {
        privateint bufferSize = 2048;
        privatestring tcpIpServerIP = "192.168.1.204";
        privateint tcpIpServerPort = 9000;
        privateSocket ClientSocket = null;
        privateManualResetEvent connectDone = newManualResetEvent(false);
        privateManualResetEvent sendDone = newManualResetEvent(false);
      
        privatevoid ConnectCallback(IAsyncResult ar)
        {
            try
            {
                Socket client = (Socket)ar.AsyncState;
                client.EndConnect(ar);
      
            }
            catch(Exception e)
            {
                OnErrorEvent(newErrorEventArgs(e));
            }
            finally
            {
                connectDone.Set();
            }
        }
        privatevoid SendCallback(IAsyncResult ar)
        {
            try
            {
                Socket client = (Socket)ar.AsyncState;
                intbytesSent = client.EndSend(ar);
            }
            catch(Exception e)
            {
                OnErrorEvent(newErrorEventArgs(e));
            }
            finally
            {
                sendDone.Set();
            }
        }
      
        /// <summary>
        /// 数据接收处理
        /// </summary>
        /// <param name="ar"></param>
        privatevoid ReceiveCallback(IAsyncResult ar)
        {
            Socket handler =null;
            try
            {
                lock(ar)
                {
                    StateObject state = (StateObject)ar.AsyncState;
                    handler = state.workSocket;
      
                    intbytesRead = handler.EndReceive(ar);
      
                    if(bytesRead > 0)
                    {
                        intReadPiont = 0;
                        while(ReadPiont < bytesRead)
                        {
                            if(state.Cortrol == 0 && ReadPiont < bytesRead)
                            {
                                longbi1 = state.buffer[ReadPiont];
                                bi1 = (bi1 << 24) & 0xff000000;
                                state.packSize = bi1;
                                ReadPiont++;
                                state.Cortrol = 1;
                            }
      
                            if(state.Cortrol == 1 && ReadPiont < bytesRead)
                            {
                                longbi1 = state.buffer[ReadPiont];
                                bi1 = (bi1 << 16) & 0x00ff0000;
                                state.packSize = state.packSize + bi1;
                                ReadPiont++;
                                state.Cortrol = 2;
                            }
      
                            if(state.Cortrol == 2 && ReadPiont < bytesRead)
                            {
                                longbi1 = state.buffer[ReadPiont];
                                bi1 = (bi1 << 8) & 0x0000ff00;
                                state.packSize = state.packSize + bi1;
                                ReadPiont++;
                                state.Cortrol = 3;
                            }
      
                            if(state.Cortrol == 3 && ReadPiont < bytesRead)
                            {
                                longbi1 = state.buffer[ReadPiont];
                                bi1 = bi1 & 0xff;
                                state.packSize = state.packSize + bi1 - 4;
                                ReadPiont++;
                                state.Cortrol = 4;
                            }
      
                            if(state.Cortrol == 4 && ReadPiont < bytesRead)
                            {
                                longbi1 = state.buffer[ReadPiont];
                                bi1 = (bi1 << 24) & 0xff000000;
                                state.residualSize = bi1;
                                ReadPiont++;
                                state.Cortrol = 5;
                                state.packSize -= 1;
                            }
      
                            if(state.Cortrol == 5 && ReadPiont < bytesRead)
                            {
                                longbi1 = state.buffer[ReadPiont];
                                bi1 = (bi1 << 16) & 0x00ff0000;
                                state.residualSize = state.residualSize + bi1;
                                ReadPiont++;
                                state.Cortrol = 6;
                                state.packSize -= 1;
                            }
      
                            if(state.Cortrol == 6 && ReadPiont < bytesRead)
                            {
                                longbi1 = state.buffer[ReadPiont];
                                bi1 = (bi1 << 8) & 0x0000ff00;
                                state.residualSize = state.residualSize + bi1;
                                ReadPiont++;
                                state.Cortrol = 7;
                                state.packSize -= 1;
                            }
                            if(state.Cortrol == 7 && ReadPiont < bytesRead)
                            {
                                longbi1 = state.buffer[ReadPiont];
                                bi1 = bi1 & 0xff;
                                state.residualSize = state.residualSize + bi1;
                                state.Datastream.SetLength(0);
                                state.Datastream.Position = 0;
      
                                ReadPiont++;
                                state.Cortrol = 8;
                                state.packSize -= 1;
                            }
      
                            if(state.Cortrol == 8 && ReadPiont < bytesRead)
                            {
                                intbi1 = bytesRead - ReadPiont;
                                intbi2 = (int)(state.residualSize - state.Datastream.Length);
                                if(bi1 >= bi2)
                                {
                                    state.Datastream.Write(state.buffer, ReadPiont, bi2);
                                    ReadPiont += bi2;
                                    OnInceptEvent(newInceptEventArgs(state.Datastream, handler));
                                    state.Cortrol = 9;
                                    state.packSize -= bi2;
                                }
                                else
                                {
                                    state.Datastream.Write(state.buffer, ReadPiont, bi1);
                                    ReadPiont += bi1;
                                    state.packSize -= bi1;
                                }
                            }
                            if(state.Cortrol == 9 && ReadPiont < bytesRead)
                            {
                                intbi1 = bytesRead - ReadPiont;
                                if(bi1 < state.packSize)
                                {
                                    state.packSize = state.packSize - bi1;
                                    ReadPiont += bi1;
                                }
                                else
                                {
                                    state.Cortrol = 0;
                                    ReadPiont += (int)state.packSize;
                                }
                            }
                        }
                    }
                    else
                    {
                        throw(new Exception("读入的数据小于1bit"));
                    }
                    if(handler.Connected == true)
                    {
                        handler.BeginReceive(state.buffer, 0, bufferSize, 0,new AsyncCallback(ReceiveCallback), state);
                        Console.WriteLine("接收字节长度【{0}】", state.buffer.Length);
                        longsize = state.residualSize;
                    }
                }
            }
            catch(Exception e)
            {
                OnErrorEvent(newErrorEventArgs(e));
      
            }
        }
      
        /// <summary>
        /// 连接服务器
        /// </summary>
        publicvoid Conn()
        {
            try
            {
                ClientSocket =new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ipAddress = IPAddress.Parse(tcpIpServerIP);
                IPEndPoint remoteEP =new IPEndPoint(ipAddress, tcpIpServerPort);
                connectDone.Reset();
                ClientSocket.BeginConnect(remoteEP,new AsyncCallback(ConnectCallback), ClientSocket);
            }
            catch(Exception e)
            {
                OnErrorEvent(newErrorEventArgs(e));
            }
      
        }
        /// <summary>
        /// 断开连接
        /// </summary>
        publicvoid Close()
        {
            try
            {
                if(ClientSocket.Connected == true)
                {
                    ClientSocket.Shutdown(SocketShutdown.Both);
                    ClientSocket.Close();
                }
            }
            catch(Exception e)
            {
                OnErrorEvent(newErrorEventArgs(e));
            }
      
        }
        /// <summary>
        /// 发送一个流数据
        /// </summary>
        /// <param name="Astream">数据流</param>
        publicvoid Send(Stream Astream)
        {
            try
            {
                if(ClientSocket.Connected == false)
                {
                    throw(new Exception("没有连接服务器不可以发送信息!"));
                }
                Astream.Position = 0;
                byte[] byteData =new byte[bufferSize];
                intbi1 = (int)((Astream.Length + 8) / bufferSize);
                intbi2 = (int)Astream.Length;
                if(((Astream.Length + 8) % bufferSize) > 0)
                {
                    bi1 = bi1 + 1;
                }
                bi1 = bi1 * bufferSize;
      
                byteData[0] = System.Convert.ToByte(bi1 >> 24);
                byteData[1] = System.Convert.ToByte((bi1 & 0x00ff0000) >> 16);
                byteData[2] = System.Convert.ToByte((bi1 & 0x0000ff00) >> 8);
                byteData[3] = System.Convert.ToByte((bi1 & 0x000000ff));
      
                byteData[4] = System.Convert.ToByte(bi2 >> 24);
                byteData[5] = System.Convert.ToByte((bi2 & 0x00ff0000) >> 16);
                byteData[6] = System.Convert.ToByte((bi2 & 0x0000ff00) >> 8);
                byteData[7] = System.Convert.ToByte((bi2 & 0x000000ff));
      
                intn = Astream.Read(byteData, 8, byteData.Length - 8);
      
                while(n > 0)
                {
                    ClientSocket.BeginSend(byteData, 0, byteData.Length, 0,new AsyncCallback(SendCallback), ClientSocket);
                    Console.WriteLine("发送字节长度【{0}】", byteData.Length);
                    sendDone.WaitOne();
                    byteData =new byte[bufferSize];
                    n = Astream.Read(byteData, 0, byteData.Length);
                }
            }
            catch(Exception e)
            {
                OnErrorEvent(newErrorEventArgs(e));
            }
        }
      
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="container">父控件</param>
        publicMyTcpIpClient(System.ComponentModel.IContainer container)
        {
            container.Add(this);
            //InitializeComponent();
      
            //
            // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
            //
        }
        /// <summary>
        /// 构造
        /// </summary>
        publicMyTcpIpClient()
        {
            Conn();
      
            //连接完成后开始循环接收服务端返回数据
            while(true)
            {
                connectDone.WaitOne();
                StateObject Cstate =new StateObject(bufferSize, ClientSocket);
                ClientSocket.BeginReceive(Cstate.buffer, 0, bufferSize, 0,
                    newAsyncCallback(ReceiveCallback), Cstate);
                Thread.Sleep(100);
            }
        }
      
        //#region Component Designer generated code
        ///// <summary>
        ///// 设计器支持所需的方法 - 不要使用代码编辑器修改
        ///// 此方法的内容。
        ///// </summary>
        //private void InitializeComponent()
        //{
        //    Conn();
        //}
        //#endregion
      
      
      
        /// <summary>
        /// 要连接的服务器IP地址
        /// </summary>
        publicstring TcpIpServerIP
        {
            get
            {
                returntcpIpServerIP;
            }
            set
            {
                tcpIpServerIP = value;
            }
        }
      
        /// <summary>
        /// 要连接的服务器所使用的端口
        /// </summary>
        publicint TcpIpServerPort
        {
            get
            {
                returntcpIpServerPort;
            }
            set
            {
                tcpIpServerPort = value;
            }
        }
      
        /// <summary>
        /// 缓冲器大小
        /// </summary>
        publicint BufferSize
        {
            get
            {
                returnbufferSize;
            }
            set
            {
                bufferSize = value;
            }
        }
      
        /// <summary>
        /// 连接的活动状态
        /// </summary>
        publicbool Activ
        {
            get
            {
                if(ClientSocket == null)
                {
                    returnfalse;
                }
                returnClientSocket.Connected;
            }
        }
        /// <summary>
        /// 接收到数据引发的事件
        /// </summary>
        publicevent InceptEvent Incept;
        /// <summary>
        /// 引发接收数据事件
        /// </summary>
        /// <param name="e">接收数据</param>
        protectedvirtual void OnInceptEvent(InceptEventArgs e)
        {
            if(Incept != null)
            {
                Incept(this, e);
            }
        }
        /// <summary>
        /// 发生错误引发的事件
        /// </summary>
        publicevent ErrorEvent Error;
        /// <summary>
        /// 引发错误事件
        /// </summary>
        /// <param name="e">错误数据</param>
        protectedvirtual void OnErrorEvent(ErrorEventArgs e)
        {
            if(Error != null)
            {
                Error(this, e);
            }
        }
      
    }
      
    /// <summary>
    /// 状态对象
    /// </summary>
    publicclass StateObject
    {
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="bufferSize">缓存</param>
        /// <param name="WorkSocket">工作的插座</param>
        publicStateObject(int bufferSize, Socket WorkSocket)
        {
            buffer =new byte[bufferSize];
            workSocket = WorkSocket;
        }
        /// <summary>
        /// 缓存
        /// </summary>
        publicbyte[] buffer = null;
        /// <summary>
        /// 工作插座
        /// </summary>
        publicSocket workSocket = null;
        /// <summary>
        /// 数据流
        /// </summary>
        publicStream Datastream = newMemoryStream();
        /// <summary>
        /// 剩余大小
        /// </summary>
        publiclong residualSize = 0;
        /// <summary>
        /// 数据包大小
        /// </summary>
        publiclong packSize = 0;
        /// <summary>
        /// 计数器
        /// </summary>
        publicint Cortrol = 0;
    }
      
    /// <summary>
    /// 接收数据事件
    /// </summary>
    publicclass InceptEventArgs : EventArgs
    {
        privatereadonly Stream datastream;
        privatereadonly Socket clientSocket;
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="Astream">接收到的数据</param>
        /// <param name="ClientSocket">接收的插座</param>
        publicInceptEventArgs(Stream Astream, Socket ClientSocket)
        {
            datastream = Astream;
            clientSocket = ClientSocket;
        }
        /// <summary>
        /// 接受的数据流
        /// </summary>
        publicStream Astream
        {
            get{ return datastream; }
        }
        /// <summary>
        /// 接收的插座
        /// </summary>
        publicSocket ClientSocket
        {
            get{ return clientSocket; }
        }
    }
    /// <summary>
    /// 定义接收委托
    /// </summary>
    publicdelegate void InceptEvent(object sender, InceptEventArgs e);
    /// <summary>
    /// 错处事件
    /// </summary>
    publicclass ErrorEventArgs : EventArgs
    {
        privatereadonly Exception error;
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="Error">错误信息对象</param>
        publicErrorEventArgs(Exception Error)
        {
            error = Error;
        }
        /// <summary>
        /// 错误信息对象
        /// </summary>
        publicException Error
        {
            get{ return error; }
        }
    }
    /// <summary>
    /// 错误委托
    /// </summary>
    publicdelegate void ErrorEvent(object sender, ErrorEventArgs e);
      
      
      
}
原文地址:http://game.ceeger.com/forum/read.php?tid=9921&fid=24
0 0
原创粉丝点击