Esempio n. 1
0
	public static TcpClient Connect( string ip, ushort port, int timeoutMSec)
	{
		TimeoutObject.Reset(); // 이벤트 상태를 초기화

		socketexception = null; // 예외발생

		string serverip = ip; // IP

		int serverport = port;

		TcpClient tcpclient = new TcpClient();

		// 비동기 접속, CallBackMethod

		tcpclient.BeginConnect( serverip, serverport, new AsyncCallback( CallBackMethod), tcpclient);

		if ( TimeoutObject.WaitOne( timeoutMSec, false)) // 동기화시킨다. timeoutMSec 동안 기다린다.
		{
			if ( IsConnectionSuccessful) // 접속되는 소켓을
				return tcpclient;
			else
				throw socketexception; // 안되면, 안된 예외를
		}
		else // 시간이 초과되면
		{
			tcpclient.Close();
			throw new TimeoutException( "TimeOut Exception");
		}
	}
Esempio n. 2
0
 public TCPClient(string ipAddress, int port, AsyncCallback connectionHandler)
 {
     client = new TcpClient();
     Debug.Log("lool");
     client.BeginConnect(ipAddress, port, connectionHandler, client);
     Debug.Log("begin");
 }
    public static bool 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)
            {
                tcpclient.Close();
                return true;
            }
            else
            {
                tcpclient.Close();
                return false;
            }
        }
        else
        {
            tcpclient.Close();
            return false;
        }
    }
Esempio n. 4
0
	private void HandleConnectionPingCompleted(object sender, PingCompletedEventArgs e)
	{
		if (m_TcpClient != null)
		{
			Disconnect();
		}
		m_TcpClient = new TcpClient();
		m_TcpClient.BeginConnect(Hostname, Port, ConnectComplete, null);
	}
Esempio n. 5
0
 /// <summary>
 /// 连接服务器
 /// </summary>
 void ConnectServer(string host, int port) {
     client = null;
     client = new TcpClient();
     client.SendTimeout = 1000;
     client.ReceiveTimeout = 1000;
     client.NoDelay = true;
     try {
         client.BeginConnect(host, port, new AsyncCallback(OnConnect), null);
     } catch (Exception e) {
         Close(); Debug.LogError(e.Message);
     }
 }
	private bool TestConnection(){
		TcpClient client = new TcpClient(); 
		bool result = false;
		try
		{
			client.BeginConnect(ip, port, null, null).AsyncWaitHandle.WaitOne(3000); 
			result = client.Connected;
		}


		catch { }
		finally {
			client.Close ();
		}
		return result;
	}
Esempio n. 7
0
 public void setupSocket()
 {
     //		try {
     //			host = hostField.text;
     //			if (string.IsNullOrEmpty(host))
     //				host = "localhost";
     //			port = int.Parse(portField.text);
     //			mySocket = new TcpClient(host, port);
     //			theStream = mySocket.GetStream();
     //			theWriter = new StreamWriter(theStream);
     //			theReader = new StreamReader(theStream);
     //			theReader.BaseStream.ReadTimeout = 1000;
     //			socketReady = true;
     //			Debug.Log ("Connected");
     //			menu.SetActive(false);
     //			world.SetActive(true);
     //			EventsManager.em.speedController.SetActive (true);
     //		}
     try {
         host = hostField.text;
         if (string.IsNullOrEmpty(host))
             host = "localhost";
         port = int.Parse(portField.text);
         mySocket = new TcpClient();
         var result = mySocket.BeginConnect(host, port, null, null);
         bool success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2));
         if (!success)
             throw new Exception("Connection timed out.");
         mySocket.EndConnect(result);
         theStream = mySocket.GetStream();
         theWriter = new StreamWriter(theStream);
         theReader = new StreamReader(theStream);
         theReader.BaseStream.ReadTimeout = 1000;
         socketReady = true;
         Debug.Log ("Connected");
         menu.SetActive(false);
         world.SetActive(true);
         EventsManager.em.speedController.SetActive (true);
         EventsManager.em.dallesPanels.SetActive (true);
     }
     catch (Exception e) {
         Debug.Log("Socket error: " + e);
         EventsManager.em.msgBox.ServerMessage("Connection failed: " + e.Message, Color.red);
         //Application.LoadLevel(0);
     }
 }
Esempio n. 8
0
	public void Connect(string host,int port)
	{
        this.Host = host;
        this.Port = port;
        begin = DateTime.Now;
        callConnectioneFun = false;
        callTimeOutFun = false;
        isConnectioned = false;
        isbegin = true;
        isConnectCall = true;
        //Debug.Log("begin connect:" + host + " :" + port + " time:" + begin.ToString());
        if (client != null)
            client.Close();
        client = new TcpClient();
        client.BeginConnect(host, port, new AsyncCallback(OnConnected), client);

	}
Esempio n. 9
0
        internal void Connect()
        {
            try
            {
                if (mSystemStop)
                {
                    return;
                }

                m_Client = new TcpClient();
                m_Client.BeginConnect(mDev.ip, mDev.port, new AsyncCallback(ConnectCallback), null);

                SendMsg(SocketMsgTypeE.Connection, SocketConnectStatusE.连接中, null);

                _mLog.Status(true, "连接中");
            }
            catch (Exception e)
            {
                //Console.WriteLine("连接失败" + DateTime.Now.ToString() + e.StackTrace);
            }
        }
Esempio n. 10
0
        private void btnVerbind_Click(object sender, EventArgs e)
        {
            /*try
             * {
             * IPAddress[] ent = Dns.GetHostAddresses("pieterjandeclippel.be");
             * return;*/

            myTcpClient = new TcpClient();
            myTcpClient.BeginConnect(IPAddress.Parse(txtServerAdres.Text), 8001, new AsyncCallback(GetConnectedToServerCallback), myTcpClient);

            btnVerbind.Enabled     = false;
            btnInloggen.Enabled    = true;
            btnRegistreren.Enabled = true;
            this.AcceptButton      = btnInloggen;

            /*}
             * catch(Exception ex)
             * {
             *      txtOntvangen.AppendText(ex.Message + Environment.NewLine);
             * }*/
        }
Esempio n. 11
0
    /// <summary>
    /// Establishes a connection with the server and initiates callback methods.
    /// </summary>
    void ConnectGameServer()
    {
        //Check for disconnect.
        if (playerSocket != null)
        {
            if (playerSocket.Connected || isConnected)
            {
                return;
            }
            playerSocket.Close();
            playerSocket = null;
        }

        playerSocket = new TcpClient();
        playerSocket.ReceiveBufferSize = 4096;
        playerSocket.SendBufferSize    = 4096;
        playerSocket.NoDelay           = false;
        Array.Resize(ref asyncBuff, 8192);
        playerSocket.BeginConnect(serverIP, serverPort, new AsyncCallback(ConnectCallback), playerSocket);
        isConnected = true;
    }
Esempio n. 12
0
 public void connect()
 {
     try
     {
         IPEndPoint ipEndPoint = (IPEndPoint) new IPEndPoint(0, 0).Create(_remoteAddress);
         tcpClient.BeginConnect(ipEndPoint.Address, ipEndPoint.Port, new AsyncCallback(ConnectCallback), tcpClient);
     }
     catch (SocketException e)
     {
         logger.Warn(e.Message);
         Init();
     }
     catch (ObjectDisposedException e)
     {
         logger.Warn(e.Message);
         Init();
     }
     catch (NullReferenceException)
     {
     }
 }
Esempio n. 13
0
        public void login(string host, int port)
        {
            PasswordAuthentication auth = listener.GetPasswordAuthentication();

            if (null != auth)
            {
                try
                {
                    socketConnection = new TcpClient();
                    socketConnection.BeginConnect(host, port, new AsyncCallback(OnConnect), auth);
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
            else
            {
                throw new Exception("Password Authentication was null");
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Copy to
        /// </summary>
        /// <param name="stream">Stream</param>
        /// <param name="endPoint">End Point</param>
        /// <param name="timeout">Timeout</param>
        public static bool ConnectoAndCopyTo(this Stream stream, IPEndPoint endPoint, TimeSpan timeout)
        {
            using (var client = new TcpClient())
            {
                var result  = client.BeginConnect(endPoint.Address, endPoint.Port, null, null);
                var success = result.AsyncWaitHandle.WaitOne(timeout);

                if (success)
                {
                    client.EndConnect(result);

                    var s = client.GetStream();
                    stream.CopyTo(s);
                    s.Flush();

                    return(true);
                }
            }

            return(false);
        }
Esempio n. 15
0
    /// <summary>
    /// 连接到服务器
    /// </summary>
    /// <param name="ip">服务器IP</param>
    /// <returns></returns>
    public void Connect()
    {
        //disCountTimer ();

        try
        {
            tcpclient = new TcpClient();
            //防止延迟,即时发送!
            tcpclient.NoDelay = true;
            tcpclient.BeginConnect(APIS.socketUrl, 10122, new AsyncCallback(ConnectCallback), tcpclient);
        }
        catch (Exception ex)
        {
            //设置标志,连接服务端失败!
            showMessageTip("服务器断开连接,请重新运行程序或稍后再试");
            MyDebug.Log("11111111111111111111111111111111");
            //	ReConnectScript.getInstance().ReConnectToServer();
            Debug.Log(ex.ToString());
            isConnected = false;
        }
    }
Esempio n. 16
0
        /// <summary>
        /// 连接服务器
        /// </summary>
        void ConnectServer(string host, int port)
        {
            OnRegister();
            string        newHost;
            AddressFamily af;

            getIPType(host, out newHost, out af);
            client                = null;
            client                = new TcpClient(af);
            client.SendTimeout    = 1000;
            client.ReceiveTimeout = 1000;
            client.NoDelay        = true;
            try
            {
                client.BeginConnect(newHost, port, new AsyncCallback(OnConnect), null);
            }
            catch (Exception e)
            {
                OnDisconnected(DisType.Exception, e.Message);
            }
        }
Esempio n. 17
0
        /// <summary>
        /// 异步方式与服务器进行连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void connectWork_DoWork(object sender, DoWorkEventArgs e)
        {
            client = new TcpClient();
            IAsyncResult result = client.BeginConnect(serverIP, 8889, null, null);

            while (!result.IsCompleted)
            {
                Thread.Sleep(100);
                AddStatus(".");
            }
            try
            {
                client.EndConnect(result);
                e.Result = "success";
            }
            catch (Exception ex)
            {
                e.Result = ex.Message;
                return;
            }
        }
Esempio n. 18
0
        public void Process(IStreamServer server)
        {
            var client = new TcpClient();

            client.BeginConnect(Address, Port, ar =>
            {
                try
                {
                    client.EndConnect(ar);
                    server.Streams[StreamIndex] = client.GetStream();
                    var connectResult           = new ConnectResponse(StreamIndex, LocalEndPoint, client.Client.RemoteEndPoint.ToString());
                    connectResult.Process(server);
                    server.WriteMessage(connectResult);
                }
                catch (Exception ex)
                {
                    Debug.Print(DateTime.Now + " " + Environment.MachineName + ": " + ex);
                    server.WriteMessage(new StreamError(StreamIndex, ex));
                }
            }, null);
        }
Esempio n. 19
0
    void ConnectToGameServer()
    {
        if (PlayerSocket != null)
        {
            if (PlayerSocket.Connected || IsConnected)
            {
                return;
            }
            PlayerSocket.Close();
            PlayerSocket = null;
        }

        PlayerSocket = new TcpClient();
        PlayerSocket.ReceiveBufferSize = 4096;
        PlayerSocket.SendBufferSize    = 4096;
        PlayerSocket.NoDelay           = false;
        Array.Resize(ref asyncBuff, 8192);
        PlayerSocket.BeginConnect(ServerIP, ServerPort, new AsyncCallback(ConnectCallback), PlayerSocket);
        IsConnected = true;
        MenuManager.instance._menu = MenuManager.Menu.Home;
    }
Esempio n. 20
0
 public static bool CheckHostPort(string hostname, int port, int PortScanTimeout = 2000)
 {
     using (var client = new TcpClient())
     {
         try
         {
             var result  = client.BeginConnect(hostname, port, null, null);
             var success = result.AsyncWaitHandle.WaitOne(PortScanTimeout);
             if (!success)
             {
                 return(false);
             }
             client.EndConnect(result);
         }
         catch
         {
             return(false);
         }
         return(true);
     }
 }
        public async Task <bool> IsPortOpen(string host, int port)
        {
            using (var client = new TcpClient())
            {
                try
                {
                    var res = client.BeginConnect(host, port, null, null);
                    var ok  = await Task.Run(() => res.AsyncWaitHandle.WaitOne(TimeOut));

                    if (ok)
                    {
                        client.EndConnect(res);
                    }
                    return(ok);
                }
                catch
                {
                    return(false);
                }
            }
        }
        private void Connect()
        {
            _tcpClient = new TcpClient();
            IAsyncResult asyncResult = _tcpClient.BeginConnect(RemoteAddress, RemotePort, null, null);

            System.Threading.WaitHandle waitHandle = asyncResult.AsyncWaitHandle;
            try
            {
                if (!asyncResult.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(_timeout), false))
                {
                    _tcpClient.Close();
                    throw new TimeoutException(string.Format("Failed to connect to {0}:{1} within {2} seconds.", RemoteAddress, RemotePort, _timeout));
                }

                _tcpClient.EndConnect(asyncResult);
            }
            finally
            {
                waitHandle.Close();
            }
        }
Esempio n. 23
0
 /// <summary>
 /// 采用Socket方式,测试数据库服务器能否建立连接
 /// </summary>
 /// <param name="host">服务器主机名或IP</param>
 /// <param name="port">端口号</param>
 /// <param name="millisecondsTimeout">等待时间,单位:毫秒</param>
 /// <returns>返回一个结果表示该地址能否建立连接</returns>
 public static bool TestConnection(string host, int port, int millisecondsTimeout)
 {
     //判断是不是本机
     host = _localhost.Contains(host) ? "127.0.0.1" : host;
     //创建TcpClient对象
     using (var client = new TcpClient())
     {
         try
         {
             //开始连接
             var ar = client.BeginConnect(host, port, null, null);
             //设置等待时间
             ar.AsyncWaitHandle.WaitOne(millisecondsTimeout);
             return(client.Connected);
         }
         catch (Exception)
         {
             return(false);
         }
     }
 }
Esempio n. 24
0
 public void Awake()
 {
     instance = this;
     Debug.Log("hellllooooo?");
     if (serverIp == null)
     { // Server: start listening for connections
         this.isServer = true;
         listener      = new TcpListener(System.Net.IPAddress.Any, Globals.port);
         listener.Start();
         listener.BeginAcceptTcpClient(OnServerConnect, null);
         Debug.Log("on wig?");
     }
     else
     { // Client: try connecting to the server
         TcpClient          client          = new TcpClient();
         TcpConnectedClient connectedClient = new TcpConnectedClient(client);
         clientList.Add(connectedClient);
         client.BeginConnect(serverIp, Globals.port, (ar) => connectedClient.EndConnect(ar), null);
         Debug.Log("oy bruv we in");
     }
 }
        public static bool TryConnect(this TcpClient tcpClient, IPEndPoint endPoint, int timeout)
        {
            IAsyncResult ar = tcpClient.BeginConnect(endPoint.Address, endPoint.Port, null, null);
            var          wh = ar.AsyncWaitHandle;

            try
            {
                if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(timeout), false))
                {
                    tcpClient.Close();
                    return(false);
                }

                tcpClient.EndConnect(ar);
                return(true);
            }
            finally
            {
                wh.Close();
            }
        }
Esempio n. 26
0
        public override void Establish()
        {
            if (IsConnected)
            {
                return;
            }

            try
            {
                m_oNetObject.BeginConnect(Address, Port, new AsyncCallback(ConnectCallback), this);

                NetworkAction?.StateChanged(State.Connecting, new StateObject(this));

                return;
            }
            catch (Exception)
            {
            }

            NetworkAction?.StateChanged(State.Error, new StateObject(this));
        }
Esempio n. 27
0
    public void Connect()
    {
        if (_tcp != null)
        {
            return;
        }

        _tcp = new TcpClient();

        try
        {
            Debug.Log("NS: Connecting");
            _tcp.BeginConnect(Host, Port, new AsyncCallback(ConnectCallback), null);
        }
        catch (Exception ex)
        {
            _tcp = null;
            Debug.LogError($"NS: {ex.Message}");
            Message(this, new StateChangedEventArgs(State.FAILED_TO_CONNECT, "failed to connect"));
        }
    }
Esempio n. 28
0
    /// <summary>
    /// Connects to server with specified IP.
    /// </summary>
    /// <returns>Hostname of server</returns>
    public string ConnectToServer(int timeout = 0)
    {
        try
        {
            client         = new TcpClient();
            client.NoDelay = true;
            Stopwatch stp = Stopwatch.StartNew();
            if (timeout > 0)
            {
                var result  = client.BeginConnect(IP, Port, null, null);
                var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(timeout));
                if (!success)
                {
                    //client.EndConnect(result);
                    client.Close();
                    throw new Exception("Failed to connect.");
                }
                else
                {
                    client.EndConnect(result);
                }
            }
            else
            {
                client.Connect(IP, Port);
            }
            stp.Restart();
            IsConnectedToServer      = true;
            client.SendBufferSize    = BufferSize;
            client.ReceiveBufferSize = BufferSize;
            Debug.WriteLine("Succesfully Connected to: " + IP + " on Port: " + Port + " time: " + stp.Elapsed.TotalMilliseconds + " ms");
            return(IP);
        }

        catch (Exception e)
        {
            //Debug.WriteLine("Connection Failed: " + e.ToString());
            return("");
        }
    }
Esempio n. 29
0
    void CreateConnection(string host, int port)
    {
        try
        {
            client         = new TcpClient();
            client.NoDelay = true;
            //client.Connect(IPAddress.Parse(host), port);
            IAsyncResult result = client.BeginConnect(IPAddress.Parse(host), port, null, null);
            __connected = result.AsyncWaitHandle.WaitOne(1000, false);

            Debug.Log("tryed");
            if (__connected)
            {
                Debug.Log("connect");
                client.EndConnect(result);
            }
            else
            {
                client.Close();
            }
        }
        catch (SocketException ex)
        {
            __connected = false;
            Debug.Log("connect error: " + ex.Message);
            client.Close();
            return;
        }

        if (__connected)
        {
            stream = client.GetStream();
            if (recvProcess == null)
            {
                recvProcess = new Thread(new ThreadStart(RecvProcess));
                recvProcess.IsBackground = true;
                recvProcess.Start();
            }
        }
    }
Esempio n. 30
0
        public static bool p(string url, int port)
        {
            int timeout = 1000;
            var result  = false;

            using (var client = new TcpClient())
            {
                try
                {
                    client.ReceiveTimeout = timeout * 1000;
                    client.SendTimeout    = timeout * 1000;
                    var asyncResult = client.BeginConnect(url, port, null, null);
                    var waitHandle  = asyncResult.AsyncWaitHandle;
                    try
                    {
                        if (!asyncResult.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(timeout), false))
                        {
                            // wait handle didn't came back in time
                            client.Close();
                        }
                        else
                        {
                            // The result was positiv
                            result = client.Connected;
                        }
                        // ensure the ending-call
                        client.EndConnect(asyncResult);
                    }
                    finally
                    {
                        // Ensure to close the wait handle.
                        waitHandle.Close();
                    }
                }
                catch
                {
                }
            }
            return(result);
        }
Esempio n. 31
0
        /// <summary>
        /// 驗證LDAP Server 是否 Alive
        /// </summary>
        /// <returns></returns>
        public bool isLdapServerConnected(string serverip, string ldapport)
        {
            //bool result = Authenticate.Instance.isLdapServerConnected();
            bool validated = false;
            int  port;

            if (string.IsNullOrEmpty(ldapport))
            {
                port = 389;
            }
            else
            {
                int.TryParse(ldapport, out port);
            }

            var client = new TcpClient();

            try
            {
                var result = client.BeginConnect(serverip, port, null, null);

                result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2)); //wait 2 second
                if (client.Connected)
                {
                    //throw new Exception("Failed to connect.");
                    validated = true;
                }
            }
            catch (Exception e)
            {
                validated = false;
            }
            finally
            {
                // we have connected
                //client.EndConnect(result);
                client.Close();
            }
            return(validated);
        }
Esempio n. 32
0
        public void Connect()
        {
            if (iBeginWait == 2)
            {
                return;
            }

            try
            {
                this._client           = new TcpClient();
                _client.ReceiveTimeout = 10;
                connectDone.Reset();
                LogInfo.SetText("Establishing Connection to " + _remote.ToString());
                _client.BeginConnect(_remote, _port, new AsyncCallback(ConnectCallback), _client); //异步连接
                if (iBeginWait != 2)
                {
                    iBeginWait = 1;
                }
                connectDone.WaitOne();    //当在派生类中重写时,阻止当前线程,直到当前的 WaitHandle 收到信号
                if (iBeginWait != 2)
                {
                    iBeginWait = 0;
                }

                if (_client?.Client != null && (_client.Connected))
                {
                    workStream = _client.GetStream();

                    LogInfo.SetText("Connection established " + _remote.ToString());

                    AsyncRead(_client);  //异步读取数据
                }
            }
            catch (Exception e)
            {
                LogInfo.SetText("连接服务器失败,错误为: " + e.Message);
                Thread.Sleep(100);
                Connected = false;
            }
        }
    public static IEnumerator ConnectServer()
    {
        _client = new TcpClient();
        //异步连接
        IAsyncResult async = _client.BeginConnect("101.200.220.209", 60002, null, null);

        while (!async.IsCompleted)
        {
            Debug.Log("连接服务器中");
            yield return(null);
        }

        try
        {
            _client.EndConnect(async);
        }
        catch (Exception ex)
        {
            isConnected = false;
            yield break;
        }
        //获取通信流
        try
        {
            _stream = _client.GetStream();
        }
        catch (Exception ex)
        {
            isConnected = false;
            yield break;
        }
        if (_stream == null)
        {
            isConnected = false;
            yield break;
        }

        // 连接成功
        isConnected = true;
    }
Esempio n. 34
0
 public void TcpOpen()
 {
     IsTCPLink = false;
     if (_MASTER != null)
     {
         _MASTER.Dispose();
     }
     if (tcpClient != null)
     {
         tcpClient.Close();
     }
     if (LAN.IsLanLink)
     {
         try
         {
             tcpClient = new TcpClient();
             //开始一个对远程主机连接的异步请求
             IAsyncResult asyncResult = tcpClient.BeginConnect(DefaultBase.IPAddress, DefaultBase.TCPPort, null, null);
             asyncResult.AsyncWaitHandle.WaitOne(500, true);
             if (!asyncResult.IsCompleted)
             {
                 tcpClient.Close();
                 IsTCPLink = false;
                 Logger.Info("连接服务器失败!:IP" + DefaultBase.IPAddress + ",port:" + DefaultBase.TCPPort);
                 return;
             }
             //由TCP客户端创建Modbus TCP的主
             _MASTER = ModbusIpMaster.CreateIp(tcpClient);
             _MASTER.Transport.Retries     = 0;    //不必调试
             _MASTER.Transport.ReadTimeout = 1500; //读取超时
             IsTCPLink = true;
         }
         catch (Exception ex)
         {
             Logger.Error(ex);
             IsTCPLink = false;
             tcpClient.Close();
         }
     }
 }
Esempio n. 35
0
        public void Connect()
        {
            int origin = Interlocked.Exchange(ref _state, _connecting);

            if (!(origin == _none || origin == _closed))
            {
                Close(false); // connecting with wrong state
                throw new InvalidOperationException("This tcp socket client is in invalid state when connecting.");
            }

            Clean();  // force to clean

            _tcpClient = _localEndPoint != null ? new TcpClient(_localEndPoint) :
                         new TcpClient(_remoteEndPoint.Address.AddressFamily);
            SetSocketOptions();

            if (_receiveBuffer == default(ArraySegment <byte>))
            {
                _receiveBuffer = _configuration.BufferManager.BorrowBuffer();
            }
            _receiveBufferOffset = 0;

            var ar = _tcpClient.BeginConnect(_remoteEndPoint.Address, _remoteEndPoint.Port, null, _tcpClient);

            if (!ar.AsyncWaitHandle.WaitOne(ConnectTimeout))
            {
                Close(false); // connect timeout
                throw new TimeoutException(string.Format(
                                               "Connect to [{0}] timeout [{1}].", _remoteEndPoint, ConnectTimeout));
            }
            _tcpClient.EndConnect(ar);

            if (Interlocked.CompareExchange(ref _state, _connected, _connecting) != _connecting)
            {
                Close(false);// connected with wrong state
                throw new InvalidOperationException("This tcp socket client is in invalid state when connected.");
            }

            HandleTcpServerConnected();
        }
Esempio n. 36
0
        /// <summary>
        /// Starts the network handler. (Connects to a minecraft server)
        /// </summary>
        public void Start()
        {
            try {
                _baseSock = new TcpClient();
                var ar = _baseSock.BeginConnect(_mainMc.ServerIp, _mainMc.ServerPort, null, null);

                using (var wh = ar.AsyncWaitHandle) {
                    if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false))
                    {
                        _baseSock.Close();
                        RaiseSocketError(this, "Failed to connect: Connection Timeout");
                        return;
                    }

                    _baseSock.EndConnect(ar);
                }
            } catch (Exception e) {
                RaiseSocketError(this, "Failed to connect: " + e.Message);
                return;
            }

            _mainMc.Running = true;

            RaiseSocketInfo(this, "Connected to server.");
            RaiseSocketDebug(this, string.Format("IP: {0} Port: {1}", _mainMc.ServerIp, _mainMc.ServerPort.ToString()));

            // -- Create our Wrapped socket.
            _baseStream = _baseSock.GetStream();
            WSock       = new Wrapped(_baseStream);
            RaiseSocketDebug(this, "Socket Created");

            DoHandshake();

            _packetHandlers = new PacketEventHandler(this);

            // -- Start network parsing.
            _handler = new Thread(NetworkPacketHandler);
            _handler.Start();
            RaiseSocketDebug(this, "Handler thread started");
        }
Esempio n. 37
0
        private T TryConnect <T>(Func <TcpClient, T> doOperation)
        {
            IAsyncResult asyncResult = null;

            var result = default(T);

            try
            {
                var client = new TcpClient();

                try
                {
                    asyncResult = client.BeginConnect(this.Host, this.Port, null, null);

                    var success = asyncResult.AsyncWaitHandle.WaitOne(100);

                    if (success)
                    {
                        result = doOperation(client);
                    }
                }
                finally
                {
                    if (asyncResult != null && client.Connected)
                    {
                        client.EndConnect(asyncResult);
                    }
                }
            }
            catch (ObjectDisposedException)
            {
                // already disposed
            }
            catch (SocketException)
            {
                // no listener
            }

            return(result);
        }
Esempio n. 38
0
        bool Check(string ip, string host, int port, int timeout)
        {
            try
            {
                var client = new TcpClient();
                var result = client.BeginConnect(ip, port, null, null);

                var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(timeout));

                if (!success)
                {
                    return(false);
                }

                // we have connected
                client.EndConnect(result);
                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
            //using (TcpClient tcpClient = new TcpClient())
            //{

            //    try
            //    {

            //        tcpClient.Connect(ip, port);
            //        return true;
            //       // Console.WriteLine("Port open");
            //    }
            //    catch (Exception)
            //    {
            //     //   Console.WriteLine("Port closed");
            //        return false;
            //    }
            //}
        }
Esempio n. 39
0
	//public CNj
	//public BotControlScript botControllScript;

	// Use this for initialization
	void Start () {
		//init
		commandList = new ArrayList ();

		if (UsingProxy) 
		{
			proxySocket = new TcpClient ();
			proxySocket.BeginConnect (ProxyURL, ProxyPort, new System.AsyncCallback (ProxySuccess),proxySocket);
		}
		else
		{
			this.tcpListener = new TcpListener(IPAddress.Any, serverPort);
			this.listenThread = new Thread(new ThreadStart(ListenForClients));
			this.listenThread.Start();
		}

		string localIP = LocalIPAddress ();

		Debug.Log ("Server Start on:"+localIP);


		ParseObject testObject = new ParseObject("GlassGame");
		testObject["ip"] = localIP;
		testObject.SaveAsync().ContinueWith(temp=>
		                                    {

			var query = ParseObject.GetQuery("GlassGame").OrderByDescending("createdAt").Limit(1);
			query.FirstAsync().ContinueWith(t =>
			                                {
				ParseObject obj = t.Result;

				Debug.Log("Insert Parse ip:"+obj["ip"]);
				Debug.Log("Parse Date:"+obj.CreatedAt);
			});

		});

	}
Esempio n. 40
0
    /// <summary>
    /// 异步连接
    /// </summary>
    public void Connect()
    {
        if ((tcp == null) || (!tcp.Connected))
        {
            try
            {
                new Thread(() =>
                {
                    tcp = new TcpClient();
                    tcp.ReceiveTimeout = 10;

                    connectDone.Reset();

                    SetText("Establishing Connection to Server");

                    tcp.BeginConnect("218.244.145.129", 12345,
                        new AsyncCallback(ConnectCallback), tcp);

                    connectDone.WaitOne();

                    if ((tcp != null) && (tcp.Connected))
                    {
                        workStream = tcp.GetStream();

                        SetText("Connection established");

                        asyncread(tcp);
                    }
                }).Start();
            }
            catch (Exception se)
            {
                Console.WriteLine(se.Message + " Conn......." + Environment.NewLine);
            }
        }
    }
 /// <summary>
 /// 连接服务器
 /// </summary>
 void ConnectServer(string host, int port) {
     client = null;
     client = new TcpClient();
     client.SendTimeout = 1000;
     client.ReceiveTimeout = 1000;
     client.NoDelay = true;
     try {
         client.BeginConnect(host, port,new AsyncCallback(OnConnect),null);
     } catch (Exception e) {
         Close();
         //Debug.LogError(e.Message);
         sockteClientState = netState.None;
         lock (NetworkManager.sEvents)
         {
             NetworkManager.AddEvent(Protocal.ConnectFailer, new ByteBuffer());
         }
     }
 }
Esempio n. 42
0
	void ConnectTo(string ip)
	{
		if (usingProxy) 
		{
			Debug.Log ("Connecting to " + ip);

			client = new TcpClient ();
			client.BeginConnect (proxyHost, proxyPort, new System.AsyncCallback (ProcessDnsInformation), client);
		}
		else
		{
			Debug.Log ("Connecting to " + ip);
			
			client = new TcpClient ();
			client.BeginConnect (ip, port, new System.AsyncCallback (ProcessDnsInformation), client);
			
		}

	}
    /*
     * this method iterates through each known server,
     * issues a GETS to each server, and then if any line contains
     * new server info, it is added into knownServers.
     */
    public void updateServers()
    {
        TcpClient c = new TcpClient();
        for (int i = 0; i < GameMatchingServer.knownServers.Count; i++) {
            Server s = (Server) GameMatchingServer.knownServers[i];
            // to avoid connecting to self, which would cause an infinite loop.
            if (s.port != GameMatchingServer.port) {
                try {
                    c = new TcpClient();
                    var result = c.BeginConnect(s.IP, s.port, null, null);
                    var success = result.AsyncWaitHandle.WaitOne(5000, true);
                    if(!success) {
                        c.Close();
                        continue;
                    } else if (c.Connected) {
                        //c.Connect(s.IP, s.port);

                        Stream str = c.GetStream();
                        StreamWriter strW = new StreamWriter(str);
                        StreamReader strR = new StreamReader(str);
                        strW.AutoFlush = true;

                        // Login as ourselves.
                        strW.WriteLine("SERVER {0}:{1}", GameMatchingServer.port,
                                GameMatchingServer.nickName);

                        strR.ReadLine();
                        string TwoHundredTest = strR.ReadLine();
                        while (TwoHundredTest.StartsWith("100")) {
                            TwoHundredTest = strR.ReadLine();
                        }

                        // loop reads all responses from client so far.
                       // while (!strR.EndOfStream) {
                       //     Console.WriteLine(strR.ReadLine());
                       // }

                        strW.WriteLine("GETS");
                        ArrayList responses = new ArrayList();
                        string[] getSResp;

                        int k = 0;
                        responses.Add(strR.ReadLine());
                        while (((string)responses[k]).StartsWith("-200")) {
                            k++;
                            responses.Add(strR.ReadLine());
                        } // all -200's should be in string array.
                        getSResp = (String[]) responses.ToArray(typeof(string));

                        parseAndAdd(getSResp);
                        str.Close();
                        c.Close();
                    }

                } catch (SocketException ex) {
                    Console.WriteLine(ex);
                    Console.WriteLine("Connection Error with server at {0}:{1}", s.IP, s.port);
                } catch (Exception e) {
                    c.Close();
                    Console.WriteLine(e);
                }
            }
        }
    }
        public ProxyAsyncState BeginConnect(IPAddress address, AsyncCallback callback, object state)
        {
            AsyncConnection conn;

            lock (_connections)
                if (_connections.TryGetValue(new IPEndPoint(address, PortNumber), out conn))
                {
                    return new ProxyAsyncState(conn.Proxy, state);
                }

            TcpClient client = new TcpClient();

            try
            {
                lock (_unfinishedConnections)
                    _unfinishedConnections.Add(address, client);
            }
            catch (ArgumentException)
            {
                throw new InvalidOperationException("Connection is under way.");
            }

            PeerProxy proxy = CreateProxy();
            try
            {
                client.BeginConnect(address, PortNumber, callback,
                                    Tuple.Create(new ConnectionAsyncResult(client, proxy, state), address));
            }
            catch (Exception)
            {
                lock (_unfinishedConnections)
                    _unfinishedConnections.Remove(address);

                throw new CannotConnectException();
            }

            return new ProxyAsyncState(proxy, state);
        }
Esempio n. 45
0
    // Coroutine for managing the connection.
    IEnumerator ConnectionCoroutine ()
    {
        // "Active Sense" message for heartbeating.
        var heartbeat = new byte[4] {0xfe, 0xff, 0xff, 0xff};

        while (true) {
            // Try to open the connection.
            for (var retryCount = 0;; retryCount++) {
                // Start to connect.
                var tempClient = new TcpClient ();
                tempClient.BeginConnect (IPAddress.Loopback, portNumber, ConnectCallback, null);
                // Wait for callback.
                isConnecting = true;
                while (isConnecting) {
                    yield return null;
                }
                // Break if the connection is established.
                if (tempClient.Connected) {
                    tcpClient = tempClient;
                    break;
                }

                // Dispose the connection.
                tempClient.Close ();
                tempClient = null;
                // Show warning and wait a second.
                if (retryCount % 3 == 0) {
					Debug.LogWarning ("Failed to connect to MIDI Bridge. Make sure to run MidiBridge.exe");
                }
                yield return new WaitForSeconds (1.0f);
            }

            // Watch the connection.
            while (tcpClient.Connected) {
                yield return new WaitForSeconds (1.0f);
                // Send a heartbeat and break if it failed.
                try {
                    tcpClient.GetStream ().Write (heartbeat, 0, heartbeat.Length);
                } catch (System.IO.IOException exception) {
                    Debug.Log (exception);
                }
            }

            // Show warning.
            Debug.LogWarning ("Disconnected from MIDI Bridge.");

            // Close the connection and retry.
            tcpClient.Close ();
            tcpClient = null;
        }
    }
Esempio n. 46
0
 public void Connect(string host, int port)
 {
     this.Host = host;
     this.Port = port;
     begin = DateTime.Now;
     callConnectioneFun = false;
     callTimeOutFun = false;
     isConnectioned = false;
     isbegin = true;
     isConnectCall = true;
     Debug.LogFormat("<color=green>begin connect:{0} :{1} time:{2}</color>", host, port, begin.ToString());
     if (client != null)
         client.Close();
     client = new TcpClient();
     client.BeginConnect(host, port, new AsyncCallback(OnConnected), client);
 }
Esempio n. 47
0
    static bool TestConnection(string ipAddress, int Port, TimeSpan waitTimeSpan)
    {
        Debug.Log("testing server connection");
        using (TcpClient tcpClient = new TcpClient())
        {
            IAsyncResult result = tcpClient.BeginConnect(ipAddress, Port, null, null);
            WaitHandle timeoutHandler = result.AsyncWaitHandle;
            try
            {
                if (!result.AsyncWaitHandle.WaitOne(waitTimeSpan, false))
                {
                    tcpClient.Close();
                    return false;
                }

                tcpClient.EndConnect(result);
            }
            catch (Exception ex)
            {
                Debug.Log("connection to server not made");
                return false;
            }
            finally
            {
                timeoutHandler.Close();
            }
            return true;
        }
    }