public BeginConnect ( IPAddress address, int port, AsyncCallback requestCallback, object state ) : IAsyncResult | ||
address | IPAddress | |
port | int | |
requestCallback | AsyncCallback | |
state | object | |
return | IAsyncResult |
public Boolean Connect(IPAddress hostAddr, Int32 hostPort, Int32 timeout) { // Create new instance of TCP client _Client = new TcpClient(); var result = _Client.BeginConnect(hostAddr, hostPort, null, null); _TransmitThread = null; result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(timeout)); if (!_Client.Connected) { return false; } // We have connected _Client.EndConnect(result); EventHandler handler = OnConnected; if(handler != null) { handler(this, EventArgs.Empty); } // Now we are connected --> start async read operation. NetworkStream networkStream = _Client.GetStream(); byte[] buffer = new byte[_Client.ReceiveBufferSize]; networkStream.BeginRead(buffer, 0, buffer.Length, OnDataReceivedHandler, buffer); // Start thread to manage transmission of messages _TransmitThreadEnd = false; _TransmitThread = new Thread(TransmitThread); _TransmitThread.Start(); return true; }
public Client(TcpClient local, TcpClient remote, String host, int port) { _local_client = local; _remote_client = remote; _remote_client.BeginConnect(host, port, OnConnect, null); }
public void Connect(int localPort, int remotePort, IPAddress remoteAddress) { IPAddress localhost = Dns.GetHostAddresses("127.0.0.1")[0]; listener = new TcpListener(localhost, localPort); BooleanEventArg arg; try { listener.Start(); } catch (Exception e) { arg = new BooleanEventArg(); arg.result = false; //localClientConnectedToRemoteServer.Set(); connected(this, arg); return; } listener.BeginAcceptTcpClient(AcceptClient, listener); client = new TcpClient(); Thread.Sleep(1000); //localClientConnectedToRemoteServer.Reset(); client.BeginConnect(remoteAddress, remotePort, ServerConnected, client); //localClientConnectedToRemoteServer.WaitOne(); }
public static TcpClient Connect(string host, int port, int timeoutMSec) { TimeoutObject.Reset(); socketexception = null; TcpClient tcpclient = new TcpClient(); tcpclient.BeginConnect(host, port, new AsyncCallback(CallBackMethod), tcpclient); if (TimeoutObject.WaitOne(timeoutMSec, false)) { if (IsConnectionSuccessful) { return tcpclient; } else { throw socketexception; } } else { tcpclient.Close(); throw new TimeoutException("TimeOut Exception"); } }
public static void Start() { if (run == true) { Stop(); return; } newsysid = 1; listener.Start(); listener.BeginAcceptTcpClient(DoAcceptTcpClientCallback, listener); foreach (var portno in portlist) { TcpClient cl = new TcpClient(); cl.BeginConnect(IPAddress.Loopback, portno, RequestCallback, cl); System.Threading.Thread.Sleep(100); } th = new System.Threading.Thread(new System.Threading.ThreadStart(mainloop)) { IsBackground = true, Name = "stream combiner" }; th.Start(); MainV2.comPort.BaseStream = new TcpSerial() {client = new TcpClient("127.0.0.1", 5750) }; MainV2.instance.doConnect(MainV2.comPort, "preset", "5750"); }
public void CheckMinecraft() { if (!NeedToUpdate("minecraft", 30)) return; TcpClient tcp = new TcpClient(); try { tcp.SendTimeout = 2000; tcp.ReceiveTimeout = 2000; tcp.NoDelay = true; tcp.Client.ReceiveTimeout = 2000; tcp.Client.SendTimeout = 2000; var async = tcp.BeginConnect(MinecraftHost, MinecraftPort, null, null); DateTime dt = DateTime.Now; while ((DateTime.Now - dt).TotalSeconds < 3 && !async.IsCompleted) System.Threading.Thread.Sleep(40); if (!async.IsCompleted) { try { tcp.Close(); } catch { { } } MinecraftOnline = false; return; } if (!tcp.Connected) { log.Fatal("Minecraft server is offline."); MinecraftOnline = false; return; } var ns = tcp.GetStream(); var sw = new StreamWriter(ns); var sr = new StreamReader(ns); ns.WriteByte(0xFE); if (ns.ReadByte() != 0xFF) throw new Exception("Invalid data"); short strlen = BitConverter.ToInt16(ns.ReadBytes(2), 0); string strtxt = Encoding.BigEndianUnicode.GetString(ns.ReadBytes(2 * strlen)); string[] strdat = strtxt.Split('§'); // Description§Players§Slots[§] MinecraftOnline = true; MinecraftSvrDescription = strdat[0]; MinecraftCurPlayers = ulong.Parse(strdat[1]); MinecraftMaxPlayers = ulong.Parse(strdat[2]); } catch (Exception n) { log.Fatal("Minecraft server check error: " + n); MinecraftOnline = false; } }
public static bool ConnValidate(String host, int port, int timeoutMSec) { bool ret = false; timeoutObject.Reset(); socketException = null; TcpClient tcpClient = new TcpClient(); tcpClient.BeginConnect(host, port, new AsyncCallback(CallBackMethod), tcpClient); if (timeoutObject.WaitOne(timeoutMSec, false)) { if (IsConnectionSuccessful) { ret = true; tcpClient.Close(); } else { //throw socketException; } } else { //throw new TimeoutException(); } tcpClient.Close(); return ret; }
public static bool Ping(string host, int port, TimeSpan timeout, out TimeSpan elapsed) { using (TcpClient tcp = new TcpClient()) { DateTime start = DateTime.Now; IAsyncResult result = tcp.BeginConnect(host, port, null, null); WaitHandle wait = result.AsyncWaitHandle; bool ok = true; try { if (!result.AsyncWaitHandle.WaitOne(timeout, false)) { tcp.Close(); ok = false; } tcp.EndConnect(result); } catch { ok = false; } finally { wait.Close(); } DateTime stop = DateTime.Now; elapsed = stop.Subtract(start); return ok; } }
private void startCommLaser() { int remotePort = 10002; String IPAddr = jaguarSetting.LaserRangeIP; firstSetupComm = true; try { //clientSocket = new TcpClient(IPAddr, remotePort); clientSocketLaser = new TcpClient(); IAsyncResult results = clientSocketLaser.BeginConnect(IPAddr, remotePort, null, null); bool success = results.AsyncWaitHandle.WaitOne(500, true); if (!success) { clientSocketLaser.Close(); clientSocketLaser = null; receivingLaser = false; pictureBoxLaser.Image = imageList1.Images[3]; } else { receivingLaser = true; threadClientLaser = new Thread(new ThreadStart(HandleClientLaser)); threadClientLaser.CurrentCulture = new CultureInfo("en-US"); threadClientLaser.Start(); pictureBoxLaser.Image = imageList1.Images[2]; } } catch { pictureBoxLaser.Image = imageList1.Images[3]; } }
/// <summary> /// Begins the connection process to the server, including the sending of a handshake once connected. /// </summary> public void Connect() { try { BaseSock = new TcpClient(); var ar = BaseSock.BeginConnect(ClientBot.Ip, ClientBot.Port, null, null); using (ar.AsyncWaitHandle) { if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false)) { BaseSock.Close(); ClientBot.RaiseErrorMessage("Failed to connect: Timeout."); return; } BaseSock.EndConnect(ar); } } catch (Exception e) { ClientBot.RaiseErrorMessage("Failed to connect: " + e.Message); return; } ClientBot.RaiseInfoMessage("Connected to server."); BaseStream = BaseSock.GetStream(); WSock = new ClassicWrapped.ClassicWrapped {_Stream = BaseStream}; DoHandshake(); _handler = new Thread(Handle); _handler.Start(); _timeoutHandler = new Thread(Timeout); _timeoutHandler.Start(); }
private static bool IsPortOpen(IPAddress ipAddress, int currentPort, int connectTimeout) { bool portIsOpen = false; using (var tcp = new TcpClient()) { IAsyncResult ar = tcp.BeginConnect(ipAddress, currentPort, null, null); using (ar.AsyncWaitHandle) { //Wait connectTimeout ms for connection. if (ar.AsyncWaitHandle.WaitOne(connectTimeout, false)) { try { tcp.EndConnect(ar); portIsOpen = true; //Connect was successful. } catch { //Server refused the connection. } } } } return portIsOpen; }
public static TcpClient Connect(IPEndPoint remoteEndPoint, int timeoutMSec) { TimeoutObject.Reset(); socketexception = null; string serverip = Convert.ToString(remoteEndPoint.Address); int serverport = remoteEndPoint.Port; TcpClient tcpclient = new TcpClient(); tcpclient.BeginConnect(serverip, serverport, new AsyncCallback(CallBackMethod), tcpclient); if (TimeoutObject.WaitOne(timeoutMSec, false)) { if (IsConnectionSuccessful) { return tcpclient; } else { throw socketexception; } } else { tcpclient.Close(); throw new TimeoutException("TimeOut Exception"); } }
public static void Start() { if (run == true) { Stop(); return; } newsysid = 1; listener.Start(); listener.BeginAcceptTcpClient(DoAcceptTcpClientCallback, listener); foreach (var portno in portlist) { TcpClient cl = new TcpClient(); cl.BeginConnect(IPAddress.Loopback, portno, RequestCallback, cl); System.Threading.Thread.Sleep(500); } th = new System.Threading.Thread(new System.Threading.ThreadStart(mainloop)) { IsBackground = true, Name = "stream combiner" }; th.Start(); }
public void Connect() { if (_client != null) return; try { ReadyState = ReadyStates.CONNECTING; _client = new TcpClient(); _connecting = true; _client.BeginConnect(_host, _port, OnRunClient, null); var waiting = new TimeSpan(); while (_connecting && waiting < ConnectTimeout) { var timeSpan = new TimeSpan(0, 0, 0, 0, 100); waiting = waiting.Add(timeSpan); Thread.Sleep(timeSpan.Milliseconds); } if (_connecting) throw new Exception("Timeout"); } catch (Exception) { Disconnect(); OnFailedConnection(null); } }
public void Connect() { try { Close(); } catch (Exception) { } client = new TcpClient(); client.NoDelay = true; IAsyncResult ar = client.BeginConnect(Host, Port, null, null); System.Threading.WaitHandle wh = ar.AsyncWaitHandle; try { if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false)) { client.Close(); throw new IOException("Connection timoeut.", new TimeoutException()); } client.EndConnect(ar); } finally { wh.Close(); } stream = client.GetStream(); stream.ReadTimeout = 10000; stream.WriteTimeout = 10000; }
void Start() { Debug.LogFormat("current thread({0}): {1}", Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.Name); try { tcp = new TcpClient(); Interlocked.Exchange(ref connectCallback, 0); var result = tcp.BeginConnect(host, port, ConnectCallback, this); if (result.IsCompleted) { state = tcp.Connected ? "connected" : "connect failed"; } else { state = "connecting"; } } catch (Exception e) { state = string.Format("excption: {0}", e.Message); if (null != tcp) { tcp.Close(); tcp = null; } } }
public static IPAddress[] GetAllHostsWithOpenPort(IPAddress start, IPAddress end) { ConsoleColor c = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Yellow; uint from = IPAddressToUInt(start); uint to = IPAddressToUInt(end); uint between = to - from; string title = Console.Title; List<IPAddress> list = new List<IPAddress>(); for (uint i = from; i <= to; i++) { Console.Title = ((double)i / between * 100) + "% | " + i; string[] temp = new IPAddress(i).ToString().Split('.'); string[] newTemp = { temp[3], temp[2], temp[1], temp[0] }; IPAddress ip = IPAddress.Parse(string.Join(".", newTemp)); try { TcpClient client = new TcpClient(); client.BeginConnect(ip, Port, new AsyncCallback(CallBack), client); } catch (SocketException) // no such host | port closed | port busy { //Console.WriteLine("{0}:{1} is not ready for your commands", ip.ToString(), Port); } } Console.Title = title; System.Threading.Thread.Sleep(5000); Console.ForegroundColor = c; return list.ToArray(); }
public SensorState DoCheckState(Server target) { try { using (TcpClient client = new TcpClient()) { var result = client.BeginConnect(target.FullyQualifiedHostName, Port, null, null); var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2)); if (!success) return SensorState.Error; client.EndConnect(result); } return SensorState.OK; } catch (SocketException) { //TODO: Check for Status return SensorState.Error; } catch (Exception) { return SensorState.Error; } }
//This method uses TCPClient to check the validity of the domain name and returns true if domain exists, and false if it doesn't private static bool IsDomainAlive(string aDomain, int aTimeoutSeconds) { System.Uri uri = new Uri(aDomain); string uriWithoutScheme = uri.Host.TrimEnd('/'); try { using (TcpClient client = new TcpClient()) { var result = client.BeginConnect(uriWithoutScheme, 80, null, null); var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(aTimeoutSeconds)); if (!success) { // Console.Write(aDomain + " ---- No such domain exists\n"); return false; } // we have connected client.EndConnect(result); return true; } } catch (Exception ex) { // Console.Write(aDomain + " ---- " + ex.Message + "\n"); } return false; }
public void Discover() { m_endpoints = new HashSet<IPEndPoint>(); //m_discover = new UdpClient(new IPEndPoint(IPAddress.Broadcast, RemoteRunner.DiscoverPort)); m_discover = new UdpClient(); m_discover.EnableBroadcast = true; var endpoint = new IPEndPoint(IPAddress.Broadcast, RemoteRunner.DiscoverPort); for (int i = 0; i < NumBroadcast; i++) { m_discover.Send(RemoteRunner.DiscoverPackage, RemoteRunner.DiscoverPackage.Length, endpoint); m_discover.BeginReceive(DiscoverCallback, null); Thread.Sleep(BroadcastDelay); } m_discover.Close(); m_clients = new List<TcpClient>(); foreach (var addr in m_endpoints) { Console.WriteLine(addr); var cl = new TcpClient(); cl.BeginConnect(addr.Address, RemoteRunner.ConnectionPort, ConnectCallback, cl); } }
public void Connect(string host, int port) { _host = host; _port = port; _tcpClient = new TcpClient(); _tcpClient.BeginConnect(_host, _port, OnConnect, _tcpClient); UsLogging.Printf(LogWndOpt.Bold, "connecting to [u]{0}:{1}[/u]...", host, port); }
public void Connect() { //string ip = "46.101.155.56"; string ip = serverIp; int port = this.port; tcpClient = new TcpClient(); tcpClient.BeginConnect(ip, port, onCompleteConnect, tcpClient); }
void MakeTCP() { Android.Util.Log.Info("-------------", "---------------------------------------------"); Android.Util.Log.Info("-------------", "---------------------------------------------"); Android.Util.Log.Info("-------------", "Begin Connect"); TcpClient tcpClient = new TcpClient(); tcpClient.BeginConnect("google.com", 80, ConnectCompleted, tcpClient); }
public bool Connect(string ip, int port) { try { Disconnect(); AutoResetEvent autoResetEvent = new AutoResetEvent(false); tcpClient = new TcpClient(); tcpClient.BeginConnect(ip, port, new AsyncCallback( delegate(IAsyncResult asyncResult) { try { tcpClient.EndConnect(asyncResult); } catch { } autoResetEvent.Set(); } ), tcpClient); if (!autoResetEvent.WaitOne()) throw new Exception(); networkStream = tcpClient.GetStream(); thread = new Thread(new ThreadStart(Read)); thread.IsBackground = true; thread.Name = "ReadThread"; thread.Start(); return true; } catch (Exception e) { ICtrl.logger.Info("Connect(...) exception:"); ICtrl.logger.Info("ip: " + ip); ICtrl.logger.Info("port: " + port); ICtrl.logger.Info(e.Message); ICtrl.logger.Info(e.Source); ICtrl.logger.Info(e.StackTrace); DBConnection.Instance.Disconnect(); Environment.Exit(0); } return false; }
/// <summary> /// Initialize the network connection /// </summary> public void Connect(string host, int port, System.Action<bool> onResult = null) { this.onResult = onResult; client = new TcpClient(); client.NoDelay = true; client.BeginConnect(host, port, new AsyncCallback(this.DoСonnect), client); isHead = true; }
public override void Connect(IPAddress ip, int port, String username) { IP = ip; Port = port; Username = username; Client = new TcpClient(); CommunicationChannel = new TcpCommunicationChannel(Client, ip, port); Client.BeginConnect(ip, port, ConnectCallBack, null); }
public Client(TcpClient local, TcpClient remote, String host, int port) { _local_client = local; _remote_client = remote; _remote_client.BeginConnect(host, port, OnConnect, null); new Thread(new ThreadStart(ProcessQueue)).Start(); }
public static int Port = 0x0000270f; // = 9999 #endregion Fields #region Methods public static IPAddress[] GetAllHostsWithOpenPort(IPAddress local) { ConsoleColor c = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Yellow; string title = Console.Title; uint subnet = IPAddressToUInt(GetSubnetMask(local)); List<IPAddress> list = new List<IPAddress>(); uint wildcard = subnet ^ 0xffffffff; uint subnetLocal = subnet & IPAddressToUInt(local); for (uint i = 0x2; i < wildcard; i++) { string[] temp = new IPAddress(i + subnetLocal).ToString().Split('.'); string[] newTemp = { temp[3], temp[2], temp[1], temp[0] }; if (newTemp[3] == "102") if (true) { }; IPAddress ip = IPAddress.Parse(string.Join(".", newTemp)); Console.Title = ((double)i / wildcard * 100) + "% | " + ip.ToString(); try { TcpClient client = new TcpClient(); client.BeginConnect(ip, Port, new AsyncCallback(CallBack), client); } catch (SocketException) // no such host | port closed | port busy { //Console.WriteLine("{0}:{1} is not ready for your commands", ip.ToString(), Port); } if ((i & 0x4fff) == 0x0) System.Threading.Thread.Sleep(5000); } Console.Title = title; //0x4ff System.Threading.Thread.Sleep(5000); Console.ForegroundColor = c; return list.ToArray(); }
public ClientCommunication(string host, int port, int timeout, ClientForm form, bool testing) { _form = form; _client = new TcpClient(); var result = _client.BeginConnect(host, port, null, null); // start connection var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(timeout)); // if successful if (success) { _stream = _client.GetStream(); Connected = true; AllowedToDisconnect = false; readThread = new Thread(ReadHandler); writeThread = new Thread(WriteHandler); pingThread = new Thread(PingHandler); readThread.Start(); writeThread.Start(); pingThread.Start(); } else { if(!testing) MessageBox.Show(String.Format("Timeout occurred connecting to server \"{0}\" on port {1}", host, port), @"Timeout"); } }
private void BTN_Start_Click(object sender, EventArgs e) { try { // Ouverture d'un socket à l'adresse et port spécifiés Int32 port = int.Parse(TB_Port.Text); TcpClient socket = new TcpClient(); var result = socket.BeginConnect(TB_AdresseIP.Text, port, null, null); // Tentative de connexion pendant 1 seconde var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1)); // Le serveur n'a pas répondu if (!success) throw new Exception("Il n'y a pas de serveur disponible"); // On a trouvé un serveur, on démarre la partie FormGame game = new FormGame(); ServerConnection conn = new ServerConnection(game, socket); game.SetConnection(conn); // On démarre le thred d'écoute du serveur Thread serverThread = new Thread(conn.ListenToServer); serverThread.Start(); while (!serverThread.IsAlive); Thread.Sleep(1); // Affichage du jeu game.ShowDialog(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }