Socket 异步通信
最近在写数据通信的时候用到的东西!希望对大家有帮助
1 /// <summary> 2 /// 获取或设置服务器IP地址 3 /// </summary> 4 public string serverIP = ""; 5 /// <summary> 6 /// 获取或设置服务器端口 7 /// </summary> 8 public int serverPort = 0; 9 /// <summary> 10 /// 连接对象 11 /// </summary> 12 private Socket conn = null; 13 /// <summary> 14 /// 监听连接对象 15 /// </summary> 16 private Socket listenSocket = null; 17 /// <summary> 18 /// 是否停止收发数据(true:停止收发;false:可以收发) 19 /// </summary> 20 private volatile bool stopFlag = true; 21 /// <summary> 22 /// 是否连接已断开(true:已断开;false:已连接) 23 /// </summary> 24 public volatile bool isSocketBroken = true; 25 private ManualResetEvent allDone = new ManualResetEvent(false); 26 /// <summary> 27 /// 抛出接收到的数据的事件 28 /// </summary> 29 public event NetInfoEventHandler.InfoEvent infoEvent; 30 /// <summary> 31 /// 抛出异常处理的事件 32 /// </summary> 33 public event ExceptionEventHandler.ExceptionEvent exceptionEvent; 34 35 /// <summary> 36 /// 可以重连的次数,默认不重连 37 /// </summary> 38 public int canReconnectNum = 0; 39 /// <summary> 40 /// 已经重连的次数 41 /// </summary> 42 public int ReconnectedNum = 0; 43 44 /// <summary> 45 /// 连接成功编码 46 /// </summary> 47 public static string SUCCESS_CONNECT = "SUCCESS"; 48 /// <summary> 49 /// 连接异常编码 50 /// </summary> 51 public static string EXCEPTION_CONNECT = "CONNECT"; 52 /// <summary> 53 /// 接收异常编码 54 /// </summary> 55 public static string EXCEPTION_RECEIVE = "RECEIVE"; 56 /// <summary> 57 /// 发送异常编码 58 /// </summary> 59 public static string EXCEPTION_SEND = "SEND"; 60 /// <summary> 61 /// 数据内容起始位置 62 /// </summary> 63 public static int GOOD_PARSER_OFFSET = 8; 64 65 /// <summary> 66 /// 写异常log的对象 67 /// </summary> 68 public WriteLog exceptionMsgLog; 69 /// <summary> 70 /// 最新接收到的数据 71 /// </summary> 72 public byte[] read; 73 /// <summary> 74 /// 最新发送的数据 75 /// </summary> 76 public byte[] write; 77 /// <summary> 78 /// 接收数据的任务 79 /// </summary> 80 private Task receiveDataTask; 81 /// <summary> 82 ///监听连接的任务 83 /// </summary> 84 private Task lisenerTask; 85 /// <summary> 86 /// 数据开始标志 87 /// </summary> 88 private char DataBeginChar = '{'; 89 /// <summary> 90 /// 数据结束标志 91 /// </summary> 92 private char DataEndChar = '}'; 93 /// <summary> 94 /// 存放不完整的数据 95 /// </summary> 96 public byte[] totalReadByte; 97 public Socket workSocket = null; 98 99 public Connection() 100 { 101 } 102 103 /// <summary> 104 /// 构造函数 105 /// </summary> 106 /// <param name="serverIp"></param> 107 /// <param name="serverPort"></param> 108 /// <param name="errorLog"></param> 109 public Connection(string serverIp,int serverPort,WriteLog errorLog) 110 { 111 this.serverIP = serverIp; 112 this.serverPort = serverPort; 113 this.exceptionMsgLog = errorLog; 114 } 115 116 /// <summary> 117 /// 构造函数 118 /// </summary> 119 /// <param name="serverIp"></param> 120 /// <param name="serverPort"></param> 121 /// <param name="errorLog"></param> 122 public Connection(string serverIp, int serverPort,int receiveBufferSize,int sendBufferSize, WriteLog errorLog) 123 { 124 this.serverIP = serverIp; 125 this.serverPort = serverPort; 126 this.exceptionMsgLog = errorLog; 127 this.read = new byte[receiveBufferSize]; 128 this.write = new byte[sendBufferSize]; 129 } 130 131 /// <summary> 132 /// 建立连接 133 /// </summary> 134 /// <returns></returns> 135 public bool connect() 136 { 137 bool ret = false; 138 139 try 140 { 141 //初始化 142 this.conn = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 143 //开始连接 144 this.conn.Connect(this.serverIP, this.serverPort); 145 //连接成功,状态设置成已连接 146 this.isSocketBroken = false; 147 //开始接收数据 148 this.stopFlag = false; 149 if (this.read == null) 150 { 151 this.read = new byte[this.conn.ReceiveBufferSize]; 152 } 153 if (this.write == null) 154 { 155 this.write = new byte[this.conn.SendBufferSize]; 156 } 157 //异步接收数据 158 SocketError socketErr; 159 this.conn.BeginReceive(this.read, 0, this.read.Length, SocketFlags.None, out socketErr, new AsyncCallback(ReadCallback), this); 160 //启动后台任务同步接收数据 161 //this.receiveDataTask = new Task(() => this.syncReceive(this.conn, 0)); 162 //this.receiveDataTask.Start(); 163 //allDone.Set(); 164 165 //连接处理成功 166 onConnectSuccess(); 167 ret = true; 168 } 169 catch (Exception ex) 170 { 171 if (this.exceptionMsgLog != null) 172 { 173 this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString()); 174 } 175 onConnectException(ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString(),EXCEPTION_CONNECT); 176 } 177 178 return ret; 179 } 180 181 /// <summary> 182 /// 连接成功的处理 183 /// </summary> 184 private void onConnectSuccess() 185 { 186 try 187 { 188 //把收到的对象转发给外面的事件 189 if (this.exceptionEvent != null) 190 { 191 exceptionEvent(this, new ExceptionEventHandler("", SUCCESS_CONNECT)); 192 } 193 //重连次数清零 194 this.ReconnectedNum = 0; 195 } 196 catch (Exception ex) 197 { 198 if (this.exceptionMsgLog != null) 199 { 200 this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString()); 201 } 202 } 203 } 204 205 /// <summary> 206 /// 连接出现异常的处理 207 /// </summary> 208 private void onConnectException(string exceptionInfo,string exceptionCode) 209 { 210 try 211 { 212 //把收到的对象转发给外面的事件 213 if (this.exceptionEvent != null) 214 { 215 exceptionEvent(this, new ExceptionEventHandler(exceptionInfo, exceptionCode)); 216 } 217 //是否要重连 218 if (this.canReconnectNum > 0) 219 { 220 if (this.ReconnectedNum < this.canReconnectNum) 221 { 222 this.ReconnectedNum++; 223 if (this.conn != null) 224 { 225 this.disconnect(); 226 } 227 this.connect(); 228 } 229 } 230 else 231 { 232 this.isSocketBroken = true; 233 if (this.conn != null) 234 { 235 this.disconnect(); 236 } 237 } 238 } 239 catch (Exception ex) 240 { 241 if (this.exceptionMsgLog != null) 242 { 243 this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString()); 244 } 245 } 246 } 247 248 /// <summary> 249 /// 接收数据出现异常的处理 250 /// </summary> 251 private void onReceiveException(string exceptionInfo, string exceptionCode) 252 { 253 try 254 { 255 onConnectException(exceptionInfo, exceptionCode); 256 } 257 catch (Exception ex) 258 { 259 if (this.exceptionMsgLog != null) 260 { 261 this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString()); 262 } 263 } 264 } 265 266 /// <summary> 267 /// 发送数据出现异常的处理 268 /// </summary> 269 private void onSendException(string exceptionInfo, string exceptionCode) 270 { 271 try 272 { 273 onConnectException(exceptionInfo, exceptionCode); 274 } 275 catch (Exception ex) 276 { 277 if (this.exceptionMsgLog != null) 278 { 279 this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString()); 280 } 281 } 282 } 283 284 /// <summary> 285 /// 建立连接 286 /// </summary> 287 /// <returns></returns> 288 public bool lisenter() 289 { 290 bool ret = false; 291 292 try 293 { 294 IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(this.serverIP), this.serverPort); 295 this.conn = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp); 296 this.conn.Bind(ipe); 297 //监听成功,状态设置成已连接 298 this.isSocketBroken = false; 299 //开始接收数据 300 this.stopFlag = false; 301 if (this.read == null) 302 { 303 this.read = new byte[this.conn.ReceiveBufferSize]; 304 } 305 if (this.write == null) 306 { 307 this.write = new byte[this.conn.SendBufferSize]; 308 } 309 //启动后台任务监听连接 310 this.lisenerTask = new Task(() => this.startListen()); 311 this.lisenerTask.Start(); 312 allDone.Set(); 313 314 //连接处理成功 315 ret = true; 316 } 317 catch (Exception ex) 318 { 319 if (this.exceptionMsgLog != null) 320 { 321 this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString()); 322 } 323 onConnectException(ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString(), EXCEPTION_CONNECT); 324 } 325 326 return ret; 327 } 328 329 private void startListen() 330 { 331 try 332 { 333 conn.Listen(100); 334 335 while (!stopFlag) 336 { 337 allDone.Reset(); 338 339 // Start an asynchronous socket to listen for connections. 340 //Console.WriteLine("Waiting for a connection..."); 341 try 342 { 343 conn.BeginAccept(new AsyncCallback(AcceptCallback), conn); 344 } 345 catch (Exception e) 346 { 347 //Console.WriteLine(e.ToString()); 348 } 349 350 // Wait until a connection is made before continuing. 351 allDone.WaitOne(); 352 } 353 } 354 catch (Exception ex) 355 { 356 if (this.exceptionMsgLog != null) 357 { 358 this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString()); 359 } 360 onConnectException(ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString(), EXCEPTION_CONNECT); 361 } 362 } 363 364 class ReadSocketState 365 { 366 public Socket socket; 367 public volatile bool isStopFlag; 368 } 369 private ReadSocketState rss = null; 370 public const int DATA_OFFSET = 4; 371 public void AcceptCallback(IAsyncResult ar) 372 { 373 try 374 { 375 Socket listenSocket = (Socket)ar.AsyncState; 376 Socket tempSocket = listenSocket.EndAccept(ar); 377 378 // Signal the main thread to continue. 379 allDone.Set(); 380 381 Connection newConn = new Connection(listenSocket.AddressFamily.ToString(),0,this.exceptionMsgLog); 382 newConn.conn = tempSocket; 383 newConn.read = new byte[tempSocket.ReceiveBufferSize]; 384 newConn.write = new byte[tempSocket.SendBufferSize]; 385 newConn.isSocketBroken = false; 386 newConn.infoEvent += new NetInfoEventHandler.InfoEvent(ClientSocket_infoEvent); 387 newConn.exceptionEvent += new ExceptionEventHandler.ExceptionEvent(ClientSocket_ExceptionEvent); 388 //异步接收数据 389 SocketError socketErr; 390 newConn.conn.BeginReceive(newConn.read, 0, newConn.read.Length, SocketFlags.None, out socketErr, new AsyncCallback(ReadCallback), newConn); 391 ////启动后台任务同步接收数据 392 //Task newTask = new Task(() => newConn.syncReceive(newConn.conn, 0)); 393 //newTask.Start(); 394 //newConn.allDone.Set(); 395 //通知有一个连接连上来了 396 if (this.exceptionEvent != null) 397 { 398 exceptionEvent(newConn, new ExceptionEventHandler("客户端有新的客户连进来了", SUCCESS_CONNECT)); 399 } 400 401 //ThreadPool.QueueUserWorkItem(new WaitCallback(syncReceive), rss); 402 } 403 catch (Exception ex) 404 { 405 if (this.exceptionMsgLog != null) 406 { 407 this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString()); 408 } 409 onConnectException(ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString(), EXCEPTION_CONNECT); 410 } 411 412 } 413 414 public void ReadCallback(IAsyncResult ar) 415 { 416 Connection con = null; 417 try 418 { 419 con = (Connection)ar.AsyncState; 420 Socket socket = con.conn; 421 // Read data from the remote device. 422 SocketError socketErr; 423 int bytesRead = socket.EndReceive(ar, out socketErr); 424 425 string temp = Encoding.UTF8.GetString(con.read); 426 if (0 == bytesRead) 427 { 428 //errorLogger.log(ZDLogger.LVL_CRITCAL, CLASS_NM, "syncReceive", "Connection is broken!"); 429 //throw new SocketException(System.Convert.ToInt32(SocketError.ConnectionReset)); 430 } 431 else 432 { 433 if (temp.IndexOf("MARKET") < 0 && temp.IndexOf("TEST") < 0) 434 { 435 this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, temp); 436 } 437 string tmp = con.analyzeData(bytesRead, con); 438 439 //if (tmp.IndexOf("MARKET") < 0) 440 //{ 441 // this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, tmp); 442 //} 443 444 //转为后台线程处理读取的数据,不阻塞主线程对数据的读取 445 if (!string.IsNullOrEmpty(tmp)) 446 { 447 this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, "启动任务前"); 448 Task task = new Task(() => do_OneReceiveData(tmp, con)); 449 task.Start(); 450 this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, "启动任务后"); 451 } 452 } 453 454 //异步接收数据 455 //SocketError socketErr; 456 con.conn.BeginReceive(con.read, 0, con.read.Length, SocketFlags.None, out socketErr, new AsyncCallback(ReadCallback), con); 457 458 } 459 catch (SocketException se) 460 { 461 if (this.exceptionMsgLog != null) 462 { 463 this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, se.StackTrace); 464 } 465 if (con != null) 466 { 467 con.onReceiveException(se.StackTrace, EXCEPTION_RECEIVE); 468 } 469 } 470 catch (Exception ex) 471 { 472 if (this.exceptionMsgLog != null) 473 { 474 this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString()); 475 } 476 if (con != null) 477 { 478 con.onReceiveException(ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString(), EXCEPTION_RECEIVE); 479 } 480 } 481 } 482 483 /// <summary> 484 /// 接收到客户端一条数据的处理 485 /// </summary> 486 /// <param name="sender"></param> 487 /// <param name="e"></param> 488 private void ClientSocket_infoEvent(Connection sender, NetInfoEventHandler e) 489 { 490 try 491 { 492 NetInfo netInfo = e.EventArg; 493 //心跳数据不处理 494 if (netInfo.code == CommandCode.HEARTBIT) 495 { 496 return; 497 } 498 if (this.infoEvent != null) 499 { 500 infoEvent(sender, new NetInfoEventHandler(netInfo)); 501 } 502 503 } 504 catch (Exception ex) 505 { 506 this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString()); 507 } 508 } 509 510 /// <summary> 511 /// 接收到客户端异常的处理 512 /// </summary> 513 /// <param name="sender"></param> 514 /// <param name="e"></param> 515 private void ClientSocket_ExceptionEvent(Connection sender, ExceptionEventHandler e) 516 { 517 try 518 { 519 string code = e.EventCode; 520 string msg = e.EventArg; 521 //把收到的对象转发给外面的事件 522 if (this.exceptionEvent != null) 523 { 524 exceptionEvent(sender, new ExceptionEventHandler(msg, code)); 525 } 526 527 } 528 catch (Exception ex) 529 { 530 this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString()); 531 } 532 } 533 534 public void syncReceive(object stateObj) 535 { 536 //ReadSocketState rss = (ReadSocketState)stateObj; 537 //Socket socket = rss.socket; 538 //try 539 //{ 540 // DateTime timeBegin = DateTime.Now; 541 542 // while (true) 543 // { 544 // if (socket == null || this.isSocketBroken) 545 // { 546 // continue; 547 // } 548 549 // //NetInfo netInfo = readClientRequestMsg(socket, 5000); 550 551 // if (socket.Poll(3000000, SelectMode.SelectRead)) // one-second timeout 552 // { 553 // int bytesRead = socket.Receive(this.read); 554 // //string temp = Encoding.UTF8.GetString(networkState.readBuffer); 555 // if (0 == bytesRead) 556 // { 557 // //errorLogger.log(ZDLogger.LVL_CRITCAL, CLASS_NM, "syncReceive", "Connection is broken!"); 558 // throw new SocketException(System.Convert.ToInt32(SocketError.ConnectionReset)); 559 // } 560 // string tmp = this.analyzeData(bytesRead); 561 562 // //转为后台线程处理读取的数据,不阻塞主线程对数据的读取 563 // if (!string.IsNullOrEmpty(tmp)) 564 // { 565 // Task task = new Task(() => this.do_OneReceiveClientData(tmp, socket)); 566 // task.Start(); 567 // } 568 // } 569 570 // if (rss.isStopFlag) 571 // { 572 // socket.Close(); 573 // break; 574 // } 575 // } 576 //} 577 //catch (System.ObjectDisposedException ode) 578 //{ 579 // // this exception means socket_ is already closed when poll() is called 580 // Console.WriteLine(ode.ToString()); 581 //} 582 //catch (Exception ex) 583 //{ 584 // if (this.exceptionMsgLog != null) 585 // { 586 // this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString()); 587 // } 588 // onConnectException(ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString(), EXCEPTION_CONNECT); 589 //} 590 591 } 592 593 public NetInfo readClientRequestMsg(Socket socket, int timeout) 594 { 595 try 596 { 597 byte[] data = syncReceive(socket, timeout); 598 // Timeout 599 if (data == null) return null; 600 601 string msg = System.Text.ASCIIEncoding.ASCII.GetString(data, GOOD_PARSER_OFFSET, data.Length - GOOD_PARSER_OFFSET); 602 603 //errorLogger.log(ZDLogger.LVL_CRITCAL, msg); 604 605 NetInfo netInfo = new NetInfo(); 606 netInfo.MyReadString(msg); 607 return netInfo; 608 } 609 catch (Exception ex) 610 { 611 if (this.exceptionMsgLog != null) 612 { 613 this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString()); 614 } 615 onConnectException(ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString(), EXCEPTION_CONNECT); 616 return null; 617 } 618 619 620 621 } 622 623 /// <summary> 624 /// 断开连接 625 /// </summary> 626 /// <returns></returns> 627 public bool disconnect() 628 { 629 bool ret = false; 630 631 try 632 { 633 //this.conn.Close(); 634 this.conn.Disconnect(true); 635 //连接断开成功,状态设置成已断开 636 this.isSocketBroken = true; 637 this.stopFlag = true; 638 if (this.receiveDataTask != null) 639 { 640 this.receiveDataTask.Dispose(); 641 this.receiveDataTask = null; 642 } 643 if (this.lisenerTask != null) 644 { 645 this.lisenerTask.Dispose(); 646 this.lisenerTask = null; 647 } 648 allDone.Set(); 649 650 //连接断开处理成功 651 ret = true; 652 } 653 catch (Exception ex) 654 { 655 if (this.exceptionMsgLog != null) 656 { 657 this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString()); 658 } 659 onConnectException(ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString(), EXCEPTION_CONNECT); 660 } 661 662 return ret; 663 } 664 665 /// <summary> 666 /// 同步接收数据(后台任务处理) 667 /// </summary> 668 /// <param name="socket"></param> 669 /// <param name="timeout"></param> 670 /// <returns></returns> 671 private byte[] syncReceive(Socket socket, int timeout) 672 { 673 try 674 { 675 DateTime timeBegin = DateTime.Now; 676 while (true) 677 { 678 if (socket == null || this.isSocketBroken) 679 { 680 continue; 681 } 682 683 if (socket.Poll(3000000, SelectMode.SelectRead)) // one-second timeout 684 { 685 int bytesRead = socket.Receive(this.read); 686 string temp = Encoding.UTF8.GetString(this.read); 687 if (0 == bytesRead) 688 { 689 //errorLogger.log(ZDLogger.LVL_CRITCAL, CLASS_NM, "syncReceive", "Connection is broken!"); 690 throw new SocketException(System.Convert.ToInt32(SocketError.ConnectionReset)); 691 } 692 if (temp.IndexOf("MARKET") < 0) 693 { 694 this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, temp); 695 } 696 string tmp = this.analyzeData(bytesRead,this); 697 698 //if (tmp.IndexOf("MARKET") < 0) 699 //{ 700 // this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, tmp); 701 //} 702 703 //转为后台线程处理读取的数据,不阻塞主线程对数据的读取 704 if (!string.IsNullOrEmpty(tmp)) 705 { 706 Task task = new Task(() => do_OneReceiveData(tmp,this)); 707 task.Start(); 708 } 709 } 710 else 711 { 712 //超时的话退出 713 //if (timeout != 0 && DateTime.Now.Subtract(timeBegin).TotalMilliseconds > timeout) 714 //break; 715 } 716 } 717 } 718 catch (System.ObjectDisposedException ode) 719 { 720 if (this.exceptionMsgLog != null) 721 { 722 this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ode.StackTrace); 723 } 724 this.onReceiveException(ode.StackTrace, EXCEPTION_RECEIVE); 725 } 726 catch (Exception ex) 727 { 728 if (this.exceptionMsgLog != null) 729 { 730 this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString()); 731 } 732 this.onReceiveException(ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString(), EXCEPTION_RECEIVE); 733 } 734 735 return null; 736 } 737 738 /// <summary> 739 /// 处理接收到的完整对象数据 740 /// </summary> 741 /// <param name="inPut"></param> 742 private void do_OneReceiveData(string inPut,Connection conn) 743 { 744 try 745 { 746 int fir = inPut.IndexOf('{'); 747 int sec = inPut.IndexOf('}'); 748 while (fir != -1 && sec != -1) 749 { 750 string obj = inPut.Substring(fir + 1, sec - fir - 1); 751 inPut = inPut.Substring(sec + 1);//删除前面完整对象的字符串 752 //===========================//处理obj 753 fir = obj.IndexOf('('); 754 sec = obj.IndexOf(')'); 755 string lenstr = obj.Substring(fir + 1, sec - 1); 756 lenstr = lenstr.Substring(4); 757 int len = int.Parse(lenstr); 758 obj = obj.Substring(sec + 1);//取完整对象的值 759 if (len == obj.Length) //完整正确的对象 760 { 761 NetInfo netInfo = new NetInfo(); 762 netInfo.MyReadString(obj); 763 //把收到的对象转发给外面的事件 764 if (infoEvent != null) 765 { 766 conn.infoEvent(conn, new NetInfoEventHandler(netInfo)); 767 } 768 } 769 fir = inPut.IndexOf('{'); 770 sec = inPut.IndexOf('}'); 771 } 772 } 773 catch (Exception ex) 774 { 775 if (this.exceptionMsgLog != null) 776 { 777 this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString()); 778 } 779 } 780 } 781 782 /// <summary> 783 /// 处理接收到客户端请求的完整对象数据 784 /// </summary> 785 /// <param name="inPut"></param> 786 private void do_OneReceiveClientData(string inPut,Connection socket) 787 { 788 try 789 { 790 int fir = inPut.IndexOf('{'); 791 int sec = inPut.IndexOf('}'); 792 while (fir != -1 && sec != -1) 793 { 794 string obj = inPut.Substring(fir + 1, sec - fir - 1); 795 inPut = inPut.Substring(sec + 1);//删除前面完整对象的字符串 796 //===========================//处理obj 797 fir = obj.IndexOf('('); 798 sec = obj.IndexOf(')'); 799 string lenstr = obj.Substring(fir + 1, sec - 1); 800 lenstr = lenstr.Substring(4); 801 int len = int.Parse(lenstr); 802 obj = obj.Substring(sec + 1);//取完整对象的值 803 if (len == obj.Length) //完整正确的对象 804 { 805 NetInfo netInfo = new NetInfo(); 806 netInfo.MyReadString(obj); 807 //把收到的对象转发给外面的事件 808 if (infoEvent != null) 809 { 810 infoEvent(socket, new NetInfoEventHandler(netInfo)); 811 } 812 } 813 fir = inPut.IndexOf('{'); 814 sec = inPut.IndexOf('}'); 815 } 816 } 817 catch (Exception ex) 818 { 819 if (this.exceptionMsgLog != null) 820 { 821 this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString()); 822 } 823 } 824 } 825 826 827 /// <summary> 828 /// 解析当前接收的数据块,并将完整的数据返回(没有完整数据返回空) 829 /// </summary> 830 /// <param name="len"></param> 831 /// <returns></returns> 832 public string analyzeData(int len,Connection con) 833 { 834 try 835 { 836 byte[] bytes = new byte[len]; 837 List<byte> list = con.read.ToList(); 838 //移除无效部分 839 list.RemoveRange(len, list.Count - len); 840 841 bytes = list.ToArray<byte>().Clone() as byte[]; 842 843 Boolean begin = false; 844 string inPut = Encoding.UTF8.GetString(bytes); 845 Boolean end = inPut.EndsWith(con.DataEndChar.ToString()); 846 if (inPut.ElementAt(0) == con.DataBeginChar) 847 { 848 begin = true; 849 } 850 851 if (begin && end) 852 { 853 //addByteToTotal(bytes); 854 return inPut; 855 } 856 else if (end) //处理最后的信息 857 { 858 859 addByteToTotal(bytes); 860 inPut = Encoding.UTF8.GetString(totalReadByte); 861 totalReadByte = null; 862 return inPut; 863 } 864 else //中间的 865 { 866 addByteToTotal(bytes); 867 inPut = Encoding.UTF8.GetString(totalReadByte); 868 int tEnd = inPut.LastIndexOf(con.DataEndChar); 869 string r = ""; 870 string l = ""; 871 if (tEnd >= 0) 872 { 873 r = inPut.Substring(0, tEnd + 1); 874 l = inPut.Substring(tEnd + 1); 875 if (l.Length > 0) 876 { 877 totalReadByte = Encoding.UTF8.GetBytes(l); 878 } 879 } 880 return r; 881 } 882 } 883 catch(Exception ex) 884 { 885 if (this.exceptionMsgLog != null) 886 { 887 this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString()); 888 } 889 this.onReceiveException(ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString(), EXCEPTION_RECEIVE); 890 return ""; 891 } 892 } 893 894 /// <summary> 895 /// 增加一个新读取的字节数组数据到总的字节数组数据中 896 /// </summary> 897 /// <param name="bytes"></param> 898 public void addByteToTotal(byte[] bytes) 899 { 900 if (bytes == null) return; 901 try 902 { 903 lock (this) 904 { 905 //用来存放原来残余的数据 906 byte[] oldData = null; 907 //用来计算残余数据的长度 908 int Count = 0; 909 if (totalReadByte != null) 910 { 911 Count = totalReadByte.Length; 912 } 913 914 if (Count != 0) 915 { 916 oldData = (byte[])totalReadByte.Clone(); 917 } 918 totalReadByte = new byte[Count + bytes.Length]; 919 if (Count > 0) 920 { 921 oldData.CopyTo(totalReadByte, 0); 922 } 923 bytes.CopyTo(totalReadByte, Count); 924 } 925 } 926 catch (Exception ex) 927 { 928 if (this.exceptionMsgLog != null) 929 { 930 this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString()); 931 } 932 this.onReceiveException(ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString(), EXCEPTION_RECEIVE); 933 } 934 } 935 936 /// <summary> 937 /// 发送netinfo数据 938 /// </summary> 939 /// <param name="obj"></param> 940 public void sendNetInfo(NetInfo obj) 941 { 942 try 943 { 944 this.sendMsg(CommonFunction.ObjectStringToBytes(obj.MyToString())); 945 } 946 catch (Exception ex) 947 { 948 if (this.exceptionMsgLog != null) 949 { 950 this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString()); 951 } 952 this.onSendException(ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString(), EXCEPTION_SEND); 953 } 954 } 955 956 /// <summary> 957 /// 发送数据 958 /// </summary> 959 /// <param name="data"></param> 960 public void sendMsg(byte[] data) 961 { 962 try 963 { 964 lock (this.conn) 965 { 966 int offset = 0; 967 int size = data.Length; 968 size += offset; 969 while (offset < size) 970 { 971 int count = this.conn.Send(data, offset, size - offset, SocketFlags.None); 972 offset += count; 973 } 974 } 975 } 976 catch (Exception ex) 977 { 978 if (this.exceptionMsgLog != null) 979 { 980 this.exceptionMsgLog.log(LogLevel.SYSTEMERROR, ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString()); 981 } 982 this.onSendException(ex.TargetSite + ex.Message + ex.StackTrace + ex.ToString(), EXCEPTION_SEND); 983 } 984 } 985 986 /// <summary> 987 /// 接收到一个完整数据的处理,在调用的类中实现这个方法来实现各自的处理逻辑 988 /// </summary> 989 /// <param name="rawMsg"></param> 990 //public abstract void onReceiveData(string data); 991 992 /// <summary> 993 /// 接收到一个监听连接发来的完整数据的处理,在调用的类中实现这个方法来实现各自的处理逻辑 994 /// </summary> 995 /// <param name="rawMsg"></param> 996 //public abstract void onReceiveClientData(string data, Socket socket); 997 998 ///// <summary> 999 ///// 接收数据出现异常的处理,在调用的类中实现这个方法来实现各自的处理逻辑 1000 ///// </summary> 1001 ///// <param name="rawMsg"></param> 1002 //public abstract void onReceiveDataException(); 1003 1004 ///// <summary> 1005 ///// 发送数据出现异常的处理,在调用的类中实现这个方法来实现各自的处理逻辑 1006 ///// </summary> 1007 ///// <param name="rawMsg"></param> 1008 //public abstract void onSendDataException(); 1009 ///// <summary> 1010 ///// 建立连接出现异常的处理,在调用的类中实现这个方法来实现各自的处理逻辑 1011 ///// </summary> 1012 ///// <param name="rawMsg"></param> 1013 //public abstract void onConnectException();