BeginConnect() public method

public BeginConnect ( IPAddress address, int port, AsyncCallback requestCallback, object state ) : IAsyncResult
address IPAddress
port int
requestCallback AsyncCallback
state object
return IAsyncResult
Beispiel #1
0
        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();
        }
Beispiel #2
0
		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;
				}
			}
		}
Beispiel #3
0
        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];

            }
        }
Beispiel #4
0
        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;
        }
Beispiel #5
0
        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 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;
            }
        }
Beispiel #7
0
    private bool CheckTcpConnection(string brokerHostname, int brokerPort)
    {
        System.Net.Sockets.TcpClient tcpClient = new System.Net.Sockets.TcpClient();
        var result = tcpClient.BeginConnect(brokerHostname, brokerPort, null, null);

        return(result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1)));
    }
Beispiel #8
0
        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;
        }
Beispiel #9
0
        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();
        }
Beispiel #10
0
        public Client(TcpClient local, TcpClient remote, String host, int port)
        {
            _local_client   = local;
            _remote_client  = remote;

            _remote_client.BeginConnect(host, port, OnConnect, null);
        }
Beispiel #11
0
        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");
            }
        }
Beispiel #12
0
        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;
            }
        }
Beispiel #13
0
        /// <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();
        }
        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);
            }
        }
Beispiel #15
0
        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;
        }
Beispiel #16
0
        //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;
        }
Beispiel #17
0
        public static System.Net.Sockets.TcpClient Connect(System.Net.IPEndPoint remoteEndPoint, int timeoutMSec)
        {
            TimeoutObject.Reset();
            socketexception = null;

            string serverip   = Convert.ToString(remoteEndPoint.Address);
            int    serverport = remoteEndPoint.Port;

            System.Net.Sockets.TcpClient tcpclient = new System.Net.Sockets.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");
            }
        }
Beispiel #18
0
        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;
            }
        }
Beispiel #19
0
        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();
        }
Beispiel #21
0
    public static bool IsPortOpen(string host, int port, int timeout = 2000, int retry = 1)
    {
        var retryCount = 0;

        while (retryCount < retry)
        {
            // Logical delay without blocking the current thread.
            if (retryCount > 0)
            {
                System.Threading.Tasks.Task.Delay(timeout).Wait();
            }
            var client = new System.Net.Sockets.TcpClient();
            try
            {
                var result  = client.BeginConnect(host, port, null, null);
                var success = result.AsyncWaitHandle.WaitOne(timeout);
                if (success)
                {
                    client.EndConnect(result);
                    return(true);
                }
            }
            catch
            {
                // ignored
            }
            finally
            {
                client.Close();
                retryCount++;
            }
        }
        return(false);
    }
        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);
            }
        }
Beispiel #23
0
        /// <summary>
        /// Connect asynchronaizly to tcp server.
        /// </summary>
        /// <param name="remoteEndPoint"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public static TCP.TcpClient Connect(IPEndPoint remoteEndPoint, int timeout)
        {
            tcpConnector.Reset();
            socketexception = null;

            string serverIp = Convert.ToString(remoteEndPoint.Address);
            int    port     = remoteEndPoint.Port;

            TCP.TcpClient tcpClient = new TCP.TcpClient();

            tcpClient.BeginConnect(serverIp, port, new AsyncCallback(CallBackMethod), tcpClient);

            if (tcpConnector.WaitOne(timeout, false))
            {
                if (IsConnected)
                {
                    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");
        }
Beispiel #25
0
 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 void Connect()
        {
			//string ip = "46.101.155.56";
			string ip = serverIp;
			int port = this.port;
            tcpClient = new TcpClient();
            tcpClient.BeginConnect(ip, port, onCompleteConnect, tcpClient);
        }
Beispiel #27
0
 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);
 }
Beispiel #28
0
 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);
 }
Beispiel #29
0
        /// <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;

        }
Beispiel #30
0
        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();
        }
Beispiel #31
0
        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>
        /// Connecte le client Tcp au serveur.
        /// </summary>
        public void Connect()
        {
            if (_tcpClient != null && _tcpClient.Connected == true)
            {
                _tcpClient.Close();
                _tcpClient = null;
            }

            _tcpClient = new System.Net.Sockets.TcpClient();
            _tcpClient.BeginConnect(_serverIP, _serverPort, this.OnConnect, this);
        }
Beispiel #33
0
        public void Connect(string host, int port)
        {
            if (client.Connected == true)
            {
                throw new Exception("Connection is already open");
            }

            this.host = host;
            this.port = port;

            client.BeginConnect(host, port, new AsyncCallback(ConnectionCallback), client);
        }
Beispiel #34
0
        internal static TransportChannel connectTcps(string target,
                                                     Options options, IOWorker ioWorker)
        {
            IpComponents tcpComponents = parseTcps(target);

            TcpClient tcpClient = new System.Net.Sockets.TcpClient();

            Int32 timeout;

            if (options.tcpConnectTimeout > 0)
            {
                timeout = options.tcpConnectTimeout;
            }
            else
            {
                timeout = Timeout.Infinite;
            }

            IAsyncResult result = tcpClient.BeginConnect(tcpComponents.hostName, tcpComponents.port, null, null);
            bool         connectionAttempted = result.AsyncWaitHandle.WaitOne(timeout);

            if (!connectionAttempted || !tcpClient.Connected)
            {
                throw new YAMIIOException("Cannot create SSL connection");
            }

            SslStream ssl = new SslStream(tcpClient.GetStream(), false,
                                          new RemoteCertificateValidationCallback(
                                              (object sender, X509Certificate cert, X509Chain chain, System.Net.Security.SslPolicyErrors errors) =>
            {
                return(true);
            })
                                          );

            try
            {
                ssl.AuthenticateAsClient(tcpComponents.hostName, new X509CertificateCollection(),
                                         System.Security.Authentication.SslProtocols.Default, false);
            }
            catch (AuthenticationException)
            {
                throw new YAMIIOException("SSL authentication error");
            }

            tcpClient.NoDelay = options.tcpNoDelay;
            tcpClient.Client.SetSocketOption(
                SocketOptionLevel.Socket,
                SocketOptionName.KeepAlive,
                options.tcpKeepAlive ? 1 : 0);

            return(new TransportChannel(ssl, options.tcpFrameSize, ioWorker));
        }
Beispiel #35
0
        public bool Connect()
        {
            if (_Client != null && _Client.Connected)
            {
                _ReadThread = new Thread(_ReadThreadFunction);
                _ReadThread.IsBackground = true;
                _ReadThread.Start(this);
                _evtStartRead.Set();
                return(true);
            }

            if (_Client == null)
            {
                _Client = new TcpClient();
            }

            _Client.SendTimeout       = (int)SendTimeout.TotalMilliseconds;
            _Client.ReceiveTimeout    = (int)ReceiveTimeout.Milliseconds;
            _Client.ReceiveBufferSize = ReceiveBufferSize;
            _Client.SendBufferSize    = SendBufferSize;

            _Client.BeginConnect(Address, Port, _ConnectCallback, _Client);

            _ReadThread = new Thread(_ReadThreadFunction);
            _ReadThread.IsBackground = true;
            _ReadThread.Start(this);
            var connSuccess = _evtConnectDone.WaitOne(TimeSpan.FromSeconds(10.0));

            if (_Client.Connected == false || !connSuccess)
            {
                if (!connSuccess)
                {
                    Console.WriteLine("Connection timeout. (>10sec)");
                }

                if (_ReadThread.IsAlive)
                {
                    try
                    {
                        _evtStartRead.Set();
                        _ReadThread.Join(new TimeSpan(0, 0, 5));
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message);
                    }
                }
                return(false);
            }
            return(true);
        }
Beispiel #36
0
 public void Launch()
 {
     if (socket != null)
     {
         return;
     }
     recvBuffer = new byte[maxBufferSize];
     dataPacker = new DataPacker();
     Debug.Log("开始连接服务器:" + ip + " 端口:" + port);
     socket = new System.Net.Sockets.TcpClient();
     socket.BeginConnect(ip, port, ConnectResult, socket);
     CoroutineUtil.Instance.Create().AppendDelay(timeout).AppendEvent(() =>
     {
         if (socket != null && !socket.Connected)
         {
             Close();
         }
     }).Start();
 }
 public void Connect()
 {
     if (IsConnecting || IsConnected)
     {
         return;
     }
     IsConnecting = true;
     recvBuffer   = new byte[maxBufferSize];
     dataPacker   = new DataPacker();
     Debug.Log("开始连接服务器:" + ip + " 端口:" + Port);
     socket = new System.Net.Sockets.TcpClient();
     socket.BeginConnect(ip, Port, ConnectResult, socket);
     //连接超时检测
     sequenceNodeConnect = socketManager.Sequence().Delay(ConnectTimeout).Event(() =>
     {
         if (IsConnecting && !IsConnected)
         {
             socket.Close();
         }
     }).Begin();
 }
Beispiel #38
0
        public static void Queue(IPAddress address, int port, int bufferSize, Action <byte[]> onBufferAvailable)
        {
            var client = new System.Net.Sockets.TcpClient();
            var state  = new State {
                OnBufferAvailable = onBufferAvailable, TcpClient = client, Buffer = new byte[bufferSize]
            };

            try
            {
                ThreadPool.QueueUserWorkItem(_ =>
                {
                    var handle = client.BeginConnect(address, port, OnClientConnected, state);
                    if (!handle.AsyncWaitHandle.WaitOne(ConnectOrReadTimeoutMilliseconds))
                    {
                        Cleanup(state);
                    }
                });
            }
            catch (Exception)
            {
                Cleanup(state);
            }
        }
        private async Task <bool> IsCheckController()
        {
            //bool result = false;

            System.Collections.ArrayList arr    = new System.Collections.ArrayList();
            System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
            for (int i = 1; i <= 253; i++)
            {
                IAsyncResult iaResult = client.BeginConnect("192.168.0." + i.ToString(), 3000, null, null);
                iaResult.AsyncWaitHandle.WaitOne(200, false);
                if (client.Connected)
                {
                    isCheckController = await APIManager.GetHello("192.168.0." + i);

                    if (isCheckController)
                    {
                        arr.Add("192.168.0." + i);
                    }
                    break;
                }
            }
            return(isCheckController);
        }
Beispiel #40
0
        public static void Connect(string ip_port)
        {
            if (isConnected == false)
            {
                try
                {
                    string ip   = ip_port.Split(':')[0];
                    int    port = int.Parse(ip_port.Split(':')[1]);

                    logger.Info("Connecting to " + ip_port);
                    clientSocket = new System.Net.Sockets.TcpClient();

                    clientSocket.BeginConnect(ip, port, new AsyncCallback(ConnectCallback), clientSocket.Client);
                    logger.Info("Connected to " + ip_port);

                    iSAPPRemoteUI.updater.Start();
                    iSAPPRemoteUI.SetServerStatText("Server stats loading...");
                }
                catch (Exception ex)
                {
                    logger.Error(ex, ex.Message);
                }
            }
        }
Beispiel #41
0
        internal void IdentificaComunicacaoAplicacaoLocalRemota()
        {
            try
            {
                CaseBusiness.Framework.BancoDados.Entidade.Configuracao conf         = null;
                CaseBusiness.Framework.BancoDados.Processo.Configuracao confProcesso = new CaseBusiness.Framework.BancoDados.Processo.Configuracao();
                conf = confProcesso.BuscarStringConexao(CaseBusiness.Framework.Configuracao.Configuracao.BancoPrincipal);
                Boolean conexaoViaIP = true;

                if (conf != null)
                {
                    IPAddress ipAddr   = null;
                    String    ipOuNome = "";
                    String    host     = "";
                    String[]  pIP      = null;
                    Int32     ipOut    = Int32.MinValue;
                    Byte[]    ip       = new Byte[4];

                    if (conf.Servidor.IndexOf(@"\") > -1)
                    {
                        ipOuNome = conf.Servidor.Remove(conf.Servidor.IndexOf(@"\")).Replace(".", "");
                    }
                    else
                    {
                        ipOuNome = conf.Servidor.Replace(".", "");
                    }

                    if (Int32.TryParse(ipOuNome, out ipOut))
                    {
                        if (conf.Servidor.IndexOf(@"\") > -1)
                        {
                            pIP = conf.Servidor.Remove(conf.Servidor.IndexOf(@"\")).Split('.');
                        }
                        else
                        {
                            pIP = conf.Servidor.Split('.');
                        }

                        ip[0] = Convert.ToByte(pIP[0]);
                        ip[1] = Convert.ToByte(pIP[1]);
                        ip[2] = Convert.ToByte(pIP[2]);
                        ip[3] = Convert.ToByte(pIP[3]);

                        ipAddr = new IPAddress(ip);

                        conexaoViaIP = true;
                    }
                    else
                    {
                        conexaoViaIP = false;

                        if (conf.Servidor.IndexOf(@"\") > -1)
                        {
                            host = conf.Servidor.Remove(conf.Servidor.IndexOf(@"\"));
                        }
                        else
                        {
                            host = conf.Servidor;
                        }
                    }

                    using (System.Net.Sockets.TcpClient tcpSocket = new System.Net.Sockets.TcpClient())
                    {
                        IAsyncResult async = null;

                        if (conexaoViaIP)
                        {
                            async = tcpSocket.BeginConnect(ipAddr, Convert.ToInt32(conf.Porta), new AsyncCallback(Result), null);
                        }
                        else
                        {
                            async = tcpSocket.BeginConnect(host, Convert.ToInt32(conf.Porta), new AsyncCallback(Result), null);
                        }

                        DateTime startTime = DateTime.Now;

                        do
                        {
                            System.Threading.Thread.Sleep(500);

                            if (async.IsCompleted)
                            {
                                break;
                            }
                        }while (DateTime.Now.Subtract(startTime).TotalSeconds < 5);

                        if (async.IsCompleted)
                        {
                            tcpSocket.EndConnect(async);
                            CaseBusiness.Framework.Configuracao.Configuracao._tipoComunicacao = TipoComunicacao.Local;
                        }

                        tcpSocket.Close();

                        if (!async.IsCompleted)
                        {
                            //DataSet ds = null;

                            //CaseWSFramework.FrameworkSoapClient fWS = new CaseWSFramework.FrameworkSoapClient();

                            //CaseWSFramework.App app = CaseWSFramework.App.CaseManagerCliente;
                            //ds = fWS.BuscarConfiguracao(app);

                            //CaseBusiness.Framework.Configuracao.Configuracao._tipoComunicacao = TipoComunicacao.Remota;
                        }
                    }
                }
            }
            catch (SocketException)
            {
                //DataSet ds = null;

                //CaseWSFramework.FrameworkSoapClient fWS = new CaseWSFramework.FrameworkSoapClient();

                //CaseWSFramework.App app = CaseWSFramework.App.CaseManagerCliente;
                //ds = fWS.BuscarConfiguracao(app);

                //CaseBusiness.Framework.Configuracao.Configuracao._tipoComunicacao = TipoComunicacao.Remota;
            }
            catch (System.Exception ex)
            {
                CaseBusiness.Framework.Configuracao.Configuracao._erroInicializacao = "Erro: " + ex.Message;
                CaseBusiness.Framework.Log.Log.LogarArquivo("Erro: " + ex.Message + " " + ex.StackTrace, CaseBusiness.Framework.Log.TipoEventoLog.Erro, "Case Framework");

                if (ex.InnerException != null)
                {
                    CaseBusiness.Framework.Log.Log.LogarArquivo("Erro: " + ex.InnerException.ToString() + " " + ex.StackTrace, CaseBusiness.Framework.Log.TipoEventoLog.Erro, "Case Framework");
                }
                throw;
            }
        }
        /// <summary>
        /// Establish a connection to the server.
        /// </summary>
        public void Connect()
        {
            if (IsConnected)
            {
                Logger?.Invoke(_Header + "already connected");
                return;
            }
            else
            {
                Logger?.Invoke(_Header + "initializing client");

                InitializeClient(_Ssl, _PfxCertFilename, _PfxPassword);

                Logger?.Invoke(_Header + "connecting to " + ServerIpPort);
            }

            _TokenSource = new CancellationTokenSource();
            _Token       = _TokenSource.Token;

            IAsyncResult ar = _Client.BeginConnect(_ServerIp, _ServerPort, null, null);
            WaitHandle   wh = ar.AsyncWaitHandle;

            try
            {
                if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(_Settings.ConnectTimeoutMs), false))
                {
                    _Client.Close();
                    throw new TimeoutException("Timeout connecting to " + ServerIpPort);
                }

                _Client.EndConnect(ar);
                _NetworkStream = _Client.GetStream();

                if (_Ssl)
                {
                    if (_Settings.AcceptInvalidCertificates)
                    {
                        _SslStream = new SslStream(_NetworkStream, false, new RemoteCertificateValidationCallback(AcceptCertificate));
                    }
                    else
                    {
                        _SslStream = new SslStream(_NetworkStream, false);
                    }

                    _SslStream.AuthenticateAsClient(_ServerIp, _SslCertCollection, SslProtocols.Tls12, !_Settings.AcceptInvalidCertificates);

                    if (!_SslStream.IsEncrypted)
                    {
                        throw new AuthenticationException("Stream is not encrypted");
                    }
                    if (!_SslStream.IsAuthenticated)
                    {
                        throw new AuthenticationException("Stream is not authenticated");
                    }
                    if (_Settings.MutuallyAuthenticate && !_SslStream.IsMutuallyAuthenticated)
                    {
                        throw new AuthenticationException("Mutual authentication failed");
                    }
                }

                if (_Keepalive.EnableTcpKeepAlives)
                {
                    EnableKeepalives();
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                wh.Close();
            }

            _IsConnected  = true;
            _LastActivity = DateTime.Now;
            _IsTimeout    = false;
            _Events.HandleConnected(this, new ClientConnectedEventArgs(ServerIpPort));
            _DataReceiver      = Task.Run(() => DataReceiver(_Token), _Token);
            _IdleServerMonitor = Task.Run(() => IdleServerMonitor(), _Token);
        }
Beispiel #43
0
        /// <summary>
        /// Establish the connection to the server.
        /// </summary>
        /// <param name="RemoteIP">The server IP address.</param>
        /// <param name="Port">The TCP port on which to connect.</param>
        /// <param name="ConnectionTimeout">The timeout for this operation in milliseonds</param>
        public void Connect(IPAddress RemoteIP, int Port, int ConnectionTimeout = 5000)
        {
            Logger.Log(Logger.Level.Info, "Attempting connection to the remote socket");

            try
            {
                if (Port < 0)
                {
                    throw new ArgumentException("Negative values not supported.", nameof(Port));
                }
                if (ConnectionTimeout < 0)
                {
                    throw new ArgumentException("ConnectionTimeout must be zero or greater.", nameof(ConnectionTimeout));
                }

                this.RemoteIP = RemoteIP ?? throw new ArgumentNullException("Null values are not supported", nameof(RemoteIP));
                this.Port     = Port;

                TokenSource = new CancellationTokenSource();
                Client      = new System.Net.Sockets.TcpClient();

                Logger.Log(Logger.Level.Debug, $"Timeout: {ConnectionTimeout}");
                Logger.Log(Logger.Level.Debug, "Beginning socket connection");

                var ar = Client.BeginConnect(RemoteIP, Port, null, null);

                try
                {
                    if (!ar.AsyncWaitHandle.WaitOne(ConnectionTimeout, false))
                    {
                        Client.Close();
                        throw new TimeoutException($"Timeout connecting to {this.RemoteIP}:{this.Port}");
                    }

                    Client.EndConnect(ar);

                    Logger.Log(Logger.Level.Info, "Connection to remote socket succeeded");

                    NetworkStream = Client.GetStream();
                    Connected     = true;
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    ar.AsyncWaitHandle.Close();
                }

                Logger.Log(Logger.Level.Info, $"Raising the {nameof(ConnectedEvent)} event");

                var args = new object[] { this, EventArgs.Empty };
                ConnectedEvent.RaiseEventSafe(ref args);

                Logger.Log(Logger.Level.Info, $"Starting socket monitoring");

                DataReceiverLoop = Task.Run(() => DataReceiver(Token), Token);
            }
            catch (Exception ex)
            {
                Logger.Log(Logger.Level.Error, $"Failed to connect to the remote socket.\n\n{ex.Message}");
                throw;
            }
        }
Beispiel #44
0
        /// <summary>
        /// Establish the connection to the server.
        /// </summary>
        public void Connect()
        {
            IAsyncResult ar = _TcpClient.BeginConnect(_ServerIp, _Port, null, null);
            WaitHandle   wh = ar.AsyncWaitHandle;

            try
            {
                if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(_ConnectTimeoutSeconds), false))
                {
                    _TcpClient.Close();
                    throw new TimeoutException("Timeout connecting to " + _ServerIp + ":" + _Port);
                }

                _TcpClient.EndConnect(ar);
                _NetworkStream = _TcpClient.GetStream();

                if (_Ssl)
                {
                    if (AcceptInvalidCertificates)
                    {
                        // accept invalid certs
                        _SslStream = new SslStream(_NetworkStream, false, new RemoteCertificateValidationCallback(AcceptCertificate));
                    }
                    else
                    {
                        // do not accept invalid SSL certificates
                        _SslStream = new SslStream(_NetworkStream, false);
                    }

                    _SslStream.AuthenticateAsClient(_ServerIp, _SslCertCollection, SslProtocols.Tls12, !AcceptInvalidCertificates);

                    if (!_SslStream.IsEncrypted)
                    {
                        throw new AuthenticationException("Stream is not encrypted");
                    }

                    if (!_SslStream.IsAuthenticated)
                    {
                        throw new AuthenticationException("Stream is not authenticated");
                    }

                    if (MutuallyAuthenticate && !_SslStream.IsMutuallyAuthenticated)
                    {
                        throw new AuthenticationException("Mutual authentication failed");
                    }
                }

                _Connected = true;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                wh.Close();
            }

            if (Connected != null)
            {
                Task.Run(() => Connected());
            }

            Task.Run(() => DataReceiver(_Token), _Token);
        }
Beispiel #45
0
        static void Main(string[] args)
        {
            try
            {
                if (args.Length == 2)
                {
                    int    port = 0;
                    string host = args[0];
                    try
                    {
                        port = Convert.ToInt32(args[1]);
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("");
                        Console.WriteLine("Could not parse port number.");
                        Console.WriteLine("");
                        Environment.Exit(2);
                    }

                    System.Net.Sockets.TcpClient tcpclient = new System.Net.Sockets.TcpClient();
                    IAsyncResult connection = tcpclient.BeginConnect(host, port, null, null);
                    System.Threading.WaitHandle waithandle = connection.AsyncWaitHandle;
                    tcpclient.SendTimeout = 3000;

                    try
                    {
                        if (!connection.AsyncWaitHandle.WaitOne(tcpclient.SendTimeout, false))
                        {
                            tcpclient.Close();
                            throw new TimeoutException();
                        }

                        tcpclient.EndConnect(connection);
                        Console.WriteLine("");
                        Console.WriteLine("Successfully connected to server.");
                        Console.WriteLine("");
                        Environment.Exit(1);
                    }
                    catch (TimeoutException)
                    {
                        Console.WriteLine("");
                        Console.WriteLine("The connection attempt timed out.");
                        Console.WriteLine("");
                        Environment.Exit(2);
                    }
                    catch (SocketException)
                    {
                        Console.WriteLine("");
                        Console.WriteLine("Connection actively refused.");
                        Console.WriteLine("");
                    }
                    finally
                    {
                        waithandle.Close();
                    }
                }
                else
                {
                    throw new ArgumentOutOfRangeException();
                }
            }
            catch (ArgumentOutOfRangeException)
            {
                Console.WriteLine("");
                Console.WriteLine("Invalid arguments");
                Console.WriteLine("");
                Environment.Exit(2);
            }
        }
Beispiel #46
0
 public void ConnectAsync(string host, int port)
 {
     ReInitSocket();
     tcpClient.BeginConnect(host, port, new AsyncCallback(ConnectCallback), null);
     Status = TcpClientStatus.Connecting;
 }
Beispiel #47
0
        /// <summary>
        /// Establish the connection to the server.
        /// </summary>
        public void Connect(int timeoutSeconds)
        {
            if (timeoutSeconds < 1)
            {
                throw new ArgumentException("TimeoutSeconds must be greater than zero seconds.");
            }

            IAsyncResult ar = _TcpClient.BeginConnect(_ServerIp, _ServerPort, null, null);
            WaitHandle   wh = ar.AsyncWaitHandle;

            try
            {
                if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(timeoutSeconds), false))
                {
                    _TcpClient.Close();
                    throw new TimeoutException("Timeout connecting to " + _ServerIp + ":" + _ServerPort);
                }

                _TcpClient.EndConnect(ar);
                _NetworkStream = _TcpClient.GetStream();

                if (_Ssl)
                {
                    if (AcceptInvalidCertificates)
                    {
                        // accept invalid certs
                        _SslStream = new SslStream(_NetworkStream, false, new RemoteCertificateValidationCallback(AcceptCertificate));
                    }
                    else
                    {
                        // do not accept invalid SSL certificates
                        _SslStream = new SslStream(_NetworkStream, false);
                    }

                    _SslStream.AuthenticateAsClient(_ServerIp, _SslCertCollection, SslProtocols.Tls12, !AcceptInvalidCertificates);

                    if (!_SslStream.IsEncrypted)
                    {
                        throw new AuthenticationException("Stream is not encrypted");
                    }

                    if (!_SslStream.IsAuthenticated)
                    {
                        throw new AuthenticationException("Stream is not authenticated");
                    }

                    if (MutuallyAuthenticate && !_SslStream.IsMutuallyAuthenticated)
                    {
                        throw new AuthenticationException("Mutual authentication failed");
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                wh.Close();
            }

            Stats = new Statistics();
            Logger?.Invoke("Starting connection monitor for: " + _ServerIp + ":" + _ServerPort);
            Task unawaited = Task.Run(() => ClientConnectionMonitor());

            ClientConnected?.Invoke(this, EventArgs.Empty);

            _IsConnected = true;
        }
Beispiel #48
-1
        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");
            }
        }
Beispiel #50
-1
        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);
            }
        }