If (testSocket = null || ipEndPoint = null) Private void ConnectToProxyServers(Socket testSocket, IPEndPoint ipEndPoint) IAsyncResult result = wrappedAction.BeginInvoke(null, null) Private void CallWithTimeout(Action action, int timeoutMilliseconds, Socket socket, IPEndPoint ipendPoint) TestSocket.Shutdown(SocketShutdown.Both) If (testSocket != null & testSocket.Connected) IPEndPoint ipEndPoint = new IPEndPoint(ip, port) ĬallWithTimeout(ConnectToProxyServers, 5000, testSocket, ipEndPoint) If (testSocket != null & NetworkingCollaboratorBase.GetResolvedConnecionIPAddress(hostName, out ip))//Use a method to resolve your IP TestSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) ` private bool CheckConnectivityForProxyHost(string hostName, int port) I had the Same problem when connecting to a Socket and I came up with the below solution ,It works Fine for me. Private void timer_connection_Tick(object sender, EventArgs e) Lb_connectStatus.Text = "Connection Established" Private void e_Completed(object sender,SocketAsyncEventArgs e) Lb_connectStatus.Text = "Connection Failed" Timer_connection.Tick+=new EventHandler(timer_connection_Tick) IPEndPoint ipEnd = new IPEndPoint(ip, iPortNo) Į.Completed+=new EventHandler(e_Completed) IPAddress ip = IPAddress.Parse(serverIp) M_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) SocketAsyncEventArgs e=new SocketAsyncEventArgs() private void connect(string ipAdd,string port) I solved the problem by using Socket.ConnectAsync Method instead of Socket.Connect Method.Īfter invoking the Socket.ConnectAsync(SocketAsyncEventArgs), start a timer (timer_connection), if time is up, check whether socket connection is connected (if(m_clientSocket.Connected)), if not, pop up timeout error. Var asyncResult = connect(socket, null, null) Private static void AsyncConnect(Socket socket, Func connect, TimeSpan timeout) Public static void Connect(this Socket socket, IPAddress addresses, int port, TimeSpan timeout)ĪsyncConnect(socket, (s, a, o) => s.BeginConnect(addresses, port, a, o), timeout) Public static void Connect(this Socket socket, string host, int port, TimeSpan timeout)ĪsyncConnect(socket, (s, a, o) => s.BeginConnect(host, port, a, o), timeout) Use it exactly as you would use the standard Connect() methods, with an extra parameter named timeout. I just wrote an extension class in order to allow timeouts in connections.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |