Advertisement
Guest User

Untitled

a guest
Apr 17th, 2014
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.59 KB | None | 0 0
  1.  
  2. AutoResetEvent _waitEvent = new AutoResetEvent(false);
  3. bool _isConnected = false;
  4. private TcpClient tcpClient;
  5. public void Connect()
  6. {
  7. Thread t = new Thread(new ThreadStart(() =>
  8. {
  9.  
  10. try
  11. {
  12. while (true)
  13. {
  14.  
  15. tcpClient = new TcpClient();
  16. tcpClient.Client.NoDelay = true;
  17. tcpClient.Client.Blocking = true;
  18. tcpClient.Client.DontFragment = false;
  19. tcpClient.Client.LingerState.Enabled = false;
  20. tcpClient.Client.LingerState.LingerTime = 0;
  21. tcpClient.Client.UseOnlyOverlappedIO = true;
  22. try
  23. {
  24. tcpClient.Connect("myhost", 8001);
  25. NetworkStream networkStream = tcpClient.GetStream();
  26. byte[] buffer = new byte[tcpClient.ReceiveBufferSize];
  27. networkStream.BeginRead(buffer, 0, buffer.Length, ReadCallback, buffer);
  28. var wasSet = _waitEvent.WaitOne(TimeSpan.FromSeconds(30));
  29. if (wasSet)
  30. {
  31. if (_isConnected)
  32. {
  33. return;
  34. }
  35. else
  36. {
  37. Thread.Sleep(TimeSpan.FromSeconds(10));
  38. continue;
  39. }
  40. }
  41. else
  42. {
  43. Thread.Sleep(TimeSpan.FromSeconds(10));
  44. continue;
  45. }
  46. }
  47. catch (Exception ex)
  48. {
  49. Thread.Sleep(TimeSpan.FromSeconds(10));
  50. continue;
  51. }
  52. }
  53. }
  54. catch (ThreadAbortException)
  55. {
  56. return;
  57. }
  58. }));
  59. t.Start();
  60. }
  61.  
  62. private void ReadCallback(IAsyncResult result)
  63. {
  64. try
  65. {
  66. int read;
  67. NetworkStream networkStream;
  68. try
  69. {
  70. networkStream = tcpClient.GetStream();
  71. read = networkStream.EndRead(result);
  72. }
  73. catch (Exception ex)
  74. {
  75. Close();
  76. return;
  77. }
  78.  
  79. if (read == 0)
  80. {
  81. Close();
  82. return;
  83. }
  84. if (!_isConnected)
  85. {
  86. _isConnected = true;
  87. _waitEvent.Set();
  88. }
  89. byte[] buffer = result.AsyncState as byte[];
  90. networkStream.BeginRead(buffer, 0, buffer.Length, ReadCallback, buffer);
  91. }
  92. catch { };
  93. }
  94.  
  95. public void Close()
  96. {
  97. try
  98. {
  99. _isConnected = false;
  100. if (tcpClient != null)
  101. tcpClient.Close();
  102. }
  103. catch
  104. {
  105.  
  106. }
  107. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement