public async Task Connect(string ip, int port) { try { await client.ConnectAsync(ip, port); connected = true; ConnectDoneEvent?.Invoke(this); } catch (SocketException) { ConnectFailedEvent?.Invoke(this); } }
private void ConnectCallback(IAsyncResult asyncResult) { Socket clientSocket; try { // Retrieve the socket from the state object. clientSocket = ( Socket )asyncResult.AsyncState; // Complete the connection. clientSocket.EndConnect(asyncResult); // Save the result as a property. this.ClientSocket = clientSocket; // Signal that the connection has been made. ConnectDoneEvent.Set(); } catch (Exception e) { Console.WriteLine(e.ToString()); } }
public void Connect() { Socket clientSocket; // Connect to a remote device. try { // Establish the remote endpoint for the socket. IPHostEntry ipHostInfo = Dns.GetHostEntry(ServerHostName); IPAddress ipAddress = ipHostInfo.AddressList[0]; IPEndPoint serverEndPoint = new IPEndPoint(ipAddress, ServerPortNumber); // Create a TCP/IP socket. clientSocket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); // Connect to the remote endpoint. clientSocket.BeginConnect(serverEndPoint, new AsyncCallback(ConnectCallback), clientSocket); ConnectDoneEvent.WaitOne(); } catch (Exception e) { Logger.WriteEntry(e.ToString()); } }