Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- AutoResetEvent _waitEvent = new AutoResetEvent(false);
- bool _isConnected = false;
- private TcpClient tcpClient;
- public void Connect()
- {
- Thread t = new Thread(new ThreadStart(() =>
- {
- try
- {
- while (true)
- {
- tcpClient = new TcpClient();
- tcpClient.Client.NoDelay = true;
- tcpClient.Client.Blocking = true;
- tcpClient.Client.DontFragment = false;
- tcpClient.Client.LingerState.Enabled = false;
- tcpClient.Client.LingerState.LingerTime = 0;
- tcpClient.Client.UseOnlyOverlappedIO = true;
- try
- {
- tcpClient.Connect("myhost", 8001);
- NetworkStream networkStream = tcpClient.GetStream();
- byte[] buffer = new byte[tcpClient.ReceiveBufferSize];
- networkStream.BeginRead(buffer, 0, buffer.Length, ReadCallback, buffer);
- var wasSet = _waitEvent.WaitOne(TimeSpan.FromSeconds(30));
- if (wasSet)
- {
- if (_isConnected)
- {
- return;
- }
- else
- {
- Thread.Sleep(TimeSpan.FromSeconds(10));
- continue;
- }
- }
- else
- {
- Thread.Sleep(TimeSpan.FromSeconds(10));
- continue;
- }
- }
- catch (Exception ex)
- {
- Thread.Sleep(TimeSpan.FromSeconds(10));
- continue;
- }
- }
- }
- catch (ThreadAbortException)
- {
- return;
- }
- }));
- t.Start();
- }
- private void ReadCallback(IAsyncResult result)
- {
- try
- {
- int read;
- NetworkStream networkStream;
- try
- {
- networkStream = tcpClient.GetStream();
- read = networkStream.EndRead(result);
- }
- catch (Exception ex)
- {
- Close();
- return;
- }
- if (read == 0)
- {
- Close();
- return;
- }
- if (!_isConnected)
- {
- _isConnected = true;
- _waitEvent.Set();
- }
- byte[] buffer = result.AsyncState as byte[];
- networkStream.BeginRead(buffer, 0, buffer.Length, ReadCallback, buffer);
- }
- catch { };
- }
- public void Close()
- {
- try
- {
- _isConnected = false;
- if (tcpClient != null)
- tcpClient.Close();
- }
- catch
- {
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement