Last active
December 11, 2015 15:51
-
-
Save wolfspider/d983a27d239fc5fa10e3 to your computer and use it in GitHub Desktop.
Socket Connection Utility Class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Net; | |
| using System.Net.Sockets; | |
| using System.Threading; | |
| using Microsoft.Framework.Logging; | |
| namespace OmniSharp | |
| { | |
| public class SocketConnection | |
| { | |
| public ILogger Logger { get; private set; } | |
| public string ContextFlag { get; private set; } | |
| public bool dthConnectSuccess = false; | |
| public SocketConnection( Socket socket, int port, string contextFlag, ILogger logger ) | |
| { | |
| Logger = logger; | |
| ContextFlag = contextFlag; | |
| Initialize(socket, port); | |
| } | |
| private void Initialize( Socket socket, int port) | |
| { | |
| socket.NoDelay = true; | |
| socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); | |
| SocketAsyncEventArgs connect = new SocketAsyncEventArgs(); | |
| connect.Completed += new EventHandler<SocketAsyncEventArgs>(SocketEventArg_Completed); | |
| connect.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, port); | |
| connect.UserToken = socket; | |
| Thread.Sleep(500); | |
| try | |
| { | |
| socket.ConnectAsync(connect); | |
| } | |
| catch (SocketException) | |
| { | |
| // this happens when the DTH isn't listening yet | |
| Logger.LogVerbose("[SocketConnection]: Socket Connection failed"); | |
| } | |
| } | |
| public void SocketEventArg_Completed(object sender, SocketAsyncEventArgs e) | |
| { | |
| switch (e.LastOperation) | |
| { | |
| case SocketAsyncOperation.Connect: | |
| var t1 = DateTime.UtcNow; | |
| var dthTimeout = TimeSpan.FromSeconds(30); | |
| while(DateTime.UtcNow - t1 < dthTimeout && !dthConnectSuccess && ContextFlag == "DnxProjectSystem") | |
| { | |
| Thread.Sleep(1000); | |
| Logger.LogInformation("Socket State: "+e.SocketError.ToString()); | |
| if (e.SocketError == SocketError.Success) | |
| { | |
| dthConnectSuccess = true; | |
| } | |
| } | |
| if(!dthConnectSuccess && ContextFlag == "DnxProjectSystem") | |
| { | |
| Logger.LogError("Connection Timed Out"); | |
| throw new SocketException((int)e.SocketError); | |
| } | |
| break; | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment