You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

99 lines
2.9 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. using Apewer.Network;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using System.Text;
  8. using System.Threading;
  9. namespace Apewer
  10. {
  11. internal class TcpInstance
  12. {
  13. private TcpServer _parent;
  14. private Socket _server;
  15. private Socket _client;
  16. private IPEndPoint _ep;
  17. private string _ip;
  18. private int _port;
  19. private ManualResetEvent _done = new ManualResetEvent(false);
  20. private int _length = 0;
  21. private byte[] _data;
  22. public TcpInstance(TcpServer parent, Socket server, Socket client)
  23. {
  24. _parent = parent;
  25. _server = server;
  26. _client = client;
  27. _ep = (IPEndPoint)_client.RemoteEndPoint;
  28. _ip = _ep.Address.ToString();
  29. _port = _ep.Port;
  30. }
  31. public void Process()
  32. {
  33. try
  34. {
  35. var vm = new TcpBuffer();
  36. vm.Socket = _client;
  37. vm.Socket.BeginReceive(vm.Buffer, 0, vm.Buffer.Length, SocketFlags.None, Callback, vm);
  38. _done.WaitOne();
  39. }
  40. catch (Exception argex) { _parent.RaiseExcepted(argex); }
  41. }
  42. private void Callback(IAsyncResult ar)
  43. {
  44. try
  45. {
  46. var buffer = (TcpBuffer)ar.AsyncState;
  47. if (buffer.Socket.Connected)
  48. {
  49. _length = buffer.Socket.EndReceive(ar);
  50. if (_length > 0)
  51. {
  52. _data = new byte[_length];
  53. Array.Copy(buffer.Buffer, 0, _data, 0, _length);
  54. _parent.RaiseReceived(_ip, _port, _data);
  55. buffer.Socket.BeginReceive(buffer.Buffer, 0, buffer.Buffer.Length, SocketFlags.None, Callback, buffer);
  56. }
  57. else
  58. {
  59. if (_client != null)
  60. {
  61. if (_client.Connected) _client.Close();
  62. _client = null;
  63. }
  64. if (_ep != null)
  65. {
  66. _parent.Remove(_ip + "-" + _port.ToString());
  67. _parent.RaiseClosed(_ip, _port);
  68. }
  69. }
  70. }
  71. else
  72. {
  73. if (!string.IsNullOrEmpty(_ip)) _parent.Close(_ip, _port);
  74. }
  75. }
  76. catch (Exception ex)
  77. {
  78. _parent.RaiseExcepted(ex);
  79. if (_client != null)
  80. {
  81. if (_client.Connected) _client.Close();
  82. _client = null;
  83. }
  84. _parent.Close(_ip, _port);
  85. }
  86. _done.Set();
  87. }
  88. }
  89. }