Exemple #1
0
        /// <summary>
        /// Connect to a specified IP. Disconnects from the current connection on successful connect.
        /// </summary>
        /// <param name="ipEndPoint">IP to connect to</param>
        public void Connect(IPEndPoint ipEndPoint)
        {
            if (ipEndPoint == null)
            {
                Log("IPEndPoint is null"); return;
            }

            lock (connectLock)
            {
                Socket clientSocket = null;

                try { clientSocket = new Socket(ipEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); }
                catch (SocketException ex)
                {
                    Log(NetUtility.Error(ECode.Client_FailedToCreateConnectionSocket));
                    Log(ex.Message);
                    clientSocket?.Dispose();
                    return;
                }

                clientSocket.NoDelay = UseNoDelay;

                try { clientSocket.Connect(ipEndPoint); }
                catch (Exception ex)
                {
                    Log(NetUtility.Error(ECode.Client_FailedToConnect));
                    Log(ex.Message);
                    clientSocket?.Dispose();
                    return;
                }

                Connection?.Dispose();
                Connection = new NetConnection(clientSocket, OnConnectionStatusChanged);
                OnConnectionAdded(Connection);

                if (AutoStartReceiver)
                {
                    Connection?.StartReceiverTask();
                }
            }
        }