예제 #1
0
    /// <summary>
    /// 尝试连接服务器
    /// </summary>
    /// <param name="address"></param>
    /// <param name="remoteport"></param>
    /// <returns></returns>
    public bool Connnect(string address, int remoteport)
    {
        Debug.Log("try to connect to " + address + " port number "+remoteport);
        if (mSocket != null && mSocket.Connected)
        {
            return true;
        }
        IPHostEntry hostEntry = Dns.GetHostEntry(address);
        foreach (IPAddress ip in hostEntry.AddressList)
        {
            try
            {
                IPEndPoint ipe = new IPEndPoint(ip, remoteport);

                //创建Socket
                mSocket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                mSocket.BeginConnect(ipe, new System.AsyncCallback(OnConnection), mSocket);
            }
            catch (Exception ex)
            {
                Debug.LogError(ex.Message);
            }
        }

        return true;
    }
예제 #2
0
    public static void StartClient()
    {
        try
        {
            byte[] bytes = File.ReadAllBytes("c:\\file.bin");
            string x = Convert.ToBase64String(bytes);

            IPHostEntry ipHostInfo = Dns.Resolve(Environment.MachineName);
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, Port);

            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            client.BeginConnect(remoteEP, ConnectCallback, client);
            ConnectDone.WaitOne();

            Send(client, x + "<EOF>");
            SendDone.WaitOne();

            Receive(client);
            ReceiveDone.WaitOne();

            client.Shutdown(SocketShutdown.Both);
            client.Close();
        }
        catch (Exception e)
        {
            throw;
        }
    }
예제 #3
0
    public AsynchronousClient(int port)
    {
        // Connect to a remote device.
        try
        {
            // Establish the remote endpoint for the socket.
            // The name of the
            // remote device is "host.contoso.com".
            IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

            // Create a TCP/IP socket.
            client = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);

            // Connect to the remote endpoint.
            client.BeginConnect(remoteEP,
                new AsyncCallback(ConnectCallback), client);
            connectDone.WaitOne();
            /*
            // Release the socket.
            client.Shutdown(SocketShutdown.Both);
            client.Close();
            */
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
예제 #4
0
파일: Client.cs 프로젝트: yangwenlong/ywl
    public static void StartClient()
    {
        // Connect to a remote device.
        try
        {

            // Establish the remote endpoint for the socket.
            // The name of the
            // remote device is "host.contoso.com".
            //IPHostEntry ipHostInfo = Dns.Resolve("user");
            //IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
            // Create a TCP/IP socket.
            client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            // Connect to the remote endpoint.
            client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);

            state = new StateObject();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
예제 #5
0
 public void Connect(string host, int port)
 {
     Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     IPAddress ipA = Dns.GetHostAddresses(host)[0];
     IPEndPoint ipEP = new IPEndPoint(ipA, port);
     newsock.BeginConnect(ipEP, new AsyncCallback(Connected), newsock);
 }
예제 #6
0
파일: client.cs 프로젝트: mono/gert
	public void OnConnect (IAsyncResult ar)
	{
		Socket socket = (Socket) ar.AsyncState;
		socket.EndConnect (ar);

		//
		// Start reading over the first connection. Note that this
		// is necessary to reproduce the bug, without this, the
		// call to BeginReceive on the second connection works
		// fine. With this however, the BeginReceive call on the
		// second connection fails with WSAEWOULDBLOCK.
		//
		byte [] buff = new byte [50];
		socket.BeginReceive (buff, 0, buff.Length, SocketFlags.None, new AsyncCallback (OnReceive), socket);

		//
		// Close immediatly the first connection.
		//
		socket.Close ();

		//
		// Establish a second connection.
		//
		socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
		socket.Blocking = false;
		socket.BeginConnect (new IPEndPoint (IPAddress.Loopback, 10000),
			new AsyncCallback (OnConnect2), socket);
	}
예제 #7
0
    void ConnectToServer()
    {
        clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        //服务器IP地址
        IPAddress ip = IPAddress.Parse(ipaddress);
        //服务器端口
        IPEndPoint ipEndpoint = new IPEndPoint(ip, port);

       // clientSocket.Connect(new IPEndPoint(IPAddress.Parse(ipaddress), port));
        //这是一个异步的建立连接,当连接建立成功时调用connectCallback方法
        IAsyncResult result = clientSocket.BeginConnect(ipEndpoint, new AsyncCallback(connectCallback), clientSocket);
        //这里做一个超时的监测,当连接超过5秒还没成功表示超时
        bool success = result.AsyncWaitHandle.WaitOne(5000, true);
        if (!success)
        {
            //超时
            //Closed();
            Debug.Log("connect Time Out");
        }
        else
        {
            //与socket建立连接成功,开启线程接受服务端数据。
            //worldpackage = new List<JFPackage.WorldPackage>();
            //Thread thread = new Thread(new ThreadStart(ReceiveSorket));
            t = new Thread(RecevieMessage);
            t.IsBackground = true;
            t.Start();
        }

       
    }
예제 #8
0
 public void ConnectSocket(string host, int port)
 {
     IPAddress[] ips = Dns.GetHostAddresses(host);
     IPEndPoint e = new IPEndPoint(ips[0], port);
     sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     sock.BeginConnect(e, cck, this);
 }
예제 #9
0
	public static void StartClient()
	{
		// Connect to a remote device.     
		try
		{
			// Establish the remote endpoint for the socket.     
			// The name of the     
			// remote device is "host.contoso.com".     
			//IPHostEntry ipHostInfo = Dns.Resolve("user");
			//IPAddress ipAddress = ipHostInfo.AddressList[0];
			IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
			IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
			// Create a TCP/IP socket.     
			Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			// Connect to the remote endpoint.     
			client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
			connectDone.WaitOne();
			// Send test data to the remote device.     
			Send(client, "This is a test<EOF>");
			sendDone.WaitOne();
			// Receive the response from the remote device.     
			Receive(client);
			receiveDone.WaitOne();

			// Release the socket.     
//			client.Shutdown(SocketShutdown.Both);
//			client.Close();

		}
		catch (Exception e)
		{
			LogMgr.LogError(e);
		}
	}
 //Universal function
 public string fUniversal(string sAction, string sUser = "", string sArgsList = "")
 {
     try
     {
         Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Create TCP/IP socket.
         connectDone.Reset();
         client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client); // Connect to the remote endpoint.
         connectDone.WaitOne();
         if (!ReferenceEquals(myException, null)) //No connection present
             throw (myException);
         sendDone.Reset();
         Send(client, sAction + "," + sUser + "," + sArgsList); // Send data to the remote device.
         sendDone.WaitOne();
         receiveDone.Reset();
         Receive(client); // Receive the response from the remote device.
         receiveDone.WaitOne();
         client.Shutdown(SocketShutdown.Both); //End connection
         client.Close();
         return response;
     }
     catch (Exception ex)
     {
         log.Debug(ex.ToString());
         throw ex;
     }
 }
    public void Connection()
    {
        if(!connected)
        {
            string ip = IP.text;
            Debug.Log("[CLIENT] Connecting to Server [" + ip + ":" + port + "]");

            try
            {
                IPAddress ipAdress = IPAddress.Parse(ip);
                IPEndPoint remoteEP = new IPEndPoint(ipAdress, port);
                PlayerPrefs.SetString ("IP_Address", ip);
                // Create a TCP/IP socket.
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                // Connect to the remote endpoint.
                client.BeginConnect( remoteEP, new AsyncCallback(ConnectCallback), client);
                connectDone.WaitOne();

                Receive(client);

            }
            catch (Exception e)
            {
                distributor.closeConnection();
            }
        }
        else
        {
            Application.Quit();
        }
    }
예제 #12
0
    public void AttemptConnection( string ipAddressString, string portString )
    {
        debugLog.ReceiveMessage ( "\tAttempting Connection to " + ipAddressString + " on " + portString );

        connecting = true;
        connectionType = ConnectionType.Connecting;
        debugLog.ReceiveMessage ( "\tConnection Type Set to Connecting" );

        try
        {

            IPAddress ipAddress = Dns.GetHostEntry ( ipAddressString ).AddressList[0];
            IPEndPoint remoteEndPoint = new IPEndPoint ( ipAddress, Convert.ToInt32 ( portString ));

            Socket client = new Socket ( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );

            client.BeginConnect ( remoteEndPoint, new AsyncCallback ( ConnectCallback ), client );

            Send ( client, "This is a test<EOF>" );

            Receive ( client );

            UnityEngine.Debug.Log ( "Response received : " + response );

            client.Shutdown ( SocketShutdown.Both );
            client.Close ();
        } catch ( Exception connectionError )
        {

            UnityEngine.Debug.LogError ( connectionError );
        }
    }
예제 #13
0
 public void Connect(string ip, int port)
 {
     IPAddress ipAddress = IPAddress.Parse(ip);
     IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
     client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
     client.NoDelay = true;
 }
예제 #14
0
    public void Connect(string ip, int port)
    {
        if (_connecting || _connected) return;
        _connecting = true;

        _serverEP = new IPEndPoint(IPAddress.Parse(ip), port);
        _connection = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        _connection.BeginConnect(_serverEP, new AsyncCallback(ConnectCallBack), null);
    }
예제 #15
0
 public void BeginConnect_EndPoint_ListeningSocket_Throws_InvalidOperation()
 {
     using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
     {
         socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
         socket.Listen(1);
         Assert.Throws<InvalidOperationException>(() => socket.BeginConnect(new IPEndPoint(IPAddress.Loopback, 1), TheAsyncCallback, null));
     }
 }
예제 #16
0
파일: client.cs 프로젝트: mono/gert
	Client ()
	{
		//
		// Establish first connection.
		//
		Socket socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
		socket.Blocking = false;
		socket.BeginConnect (new IPEndPoint (IPAddress.Loopback, 10000),
			new AsyncCallback (OnConnect), socket);
	}
예제 #17
0
파일: Server.cs 프로젝트: pyrobot/plong
    public static void BeginConnect(string host, int port)
    {
        IPAddress[] IPs = Dns.GetHostAddresses(host);

        Socket s = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream,
            ProtocolType.Tcp);
        s.BeginConnect(IPs[0], port,
            new AsyncCallback(ConnectCallback), s);
    }
예제 #18
0
 static void ThreadProc(object o)
 {
     try{
     var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     socket.BeginConnect(new IPEndPoint(IPAddress.Parse("66.102.13.106"), 80), new AsyncCallback(ConnectCallback1), null);
     } finally {
         Console.WriteLine(GetCurrentWin32ThreadId()+" is Outta here");
     }
     //Thread.Sleep(300);
 }
    public static void StartClient()
    {
        // Connect to a remote device.
        try
        {
            // Establish the remote endpoint for the socket.
            // The name of the 
            // remote device is "host.contoso.com".
            IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

            // Create a TCP/IP socket.
            Socket client = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);

            // Connect to the remote endpoint.
            client.BeginConnect(remoteEP,
                new AsyncCallback(ConnectCallback), client);
            connectDone.WaitOne();

            // Send test data to the remote device.
            //string fileName = @"D:\OTC_Batch\itemCode_700_14112014059522584.xml<EOF>";
            
            string fileName = @"D:\OTC_Batch\itemCode_700_14112014059522584.xml";

            string text = fileName;//System.IO.File.ReadAllText(fileName);

            text = text + "<EOF>";

            Send(client, text);

            sendDone.WaitOne();

            // Receive the response from the remote device.
            Receive(client);
            receiveDone.WaitOne();

            // Write the response to the console.
            Console.WriteLine("Response received : {0}", response);

            // Release the socket.
            client.Shutdown(SocketShutdown.Both);
            client.Close();

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
예제 #20
0
    private static void StartClient()
    {
        // Connect to a remote device.
        Console.WriteLine("Enter your message to the server: ");
        string message = Console.ReadLine();
        try
        {
            // Establish the remote endpoint for the socket.
            // The name of the 
            // remote device is "host.contoso.com".
            IPHostEntry ipHostInfo = Dns.Resolve("192.168.1.79");
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

            // Create a TCP/IP socket.
            Socket client = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);

            // Connect to the remote endpoint.
            client.BeginConnect(remoteEP,
                new AsyncCallback(ConnectCallback), client);
            connectDone.WaitOne();

            
            // Send test data to the remote device.
            Send(client, message+"<EOF>");
            sendDone.WaitOne();

            // Receive the response from the remote device.
            Receive(client);
            receiveDone.WaitOne();

            // Write the response to the console.
            Console.WriteLine("Response received : {0}", response);
            Console.ReadLine();

            // Release the socket.
            client.Shutdown(SocketShutdown.Both);
            client.Close();

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
            Console.ReadLine();
        }
    }
예제 #21
0
파일: Main.cs 프로젝트: hproof/notes
	IEnumerator TestSocket (string host, AddressFamily af, string ip)
	{
		Log ("TestSocket, {0}, {1}({2})", af, host, ip);

		// new
		var s = new Socket (af, SocketType.Stream, ProtocolType.Tcp);
		var info = new SocketInfo () {
			socket = s,
		};

		// connect
		Log ("  connect ...");
		try {
			s.BeginConnect (ip, port, OnConnect, info);
			
		} catch (Exception e) {
			Log ("err:{0}", e.Message);
		}
		var timeout = Time.time + 5;
		while (!info.has_connect) {
			yield return null;
			if (Time.time >= timeout) {
				Log ("  connect ... timeout");
				yield break;
			}
		}
		Log ("  connect ...done");

		// send 
		var str = "GET / HTTP/1.1\n"
		          + "Host: " + host + "\n"
		          + "Accept: */*\n"
		          + "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)\n"
		          + "Connection: Keep-Alive\n"
		          + "\n\n";
		yield return StartCoroutine (Send (info, str));

		// recv
		yield return StartCoroutine (Recv (info));


		// close 
		s.Close ();
	}
예제 #22
0
 public override int StartMain(IPEndPoint _ipMyPoint,IPEndPoint _ipTargetPoint)
 {
     ipMyPoint = _ipMyPoint;
         ipTargetPoint = _ipTargetPoint;
         MySocket = new Socket(ipMyPoint.Address.AddressFamily,SocketType.Stream,ProtocolType.Tcp);
         MessageServiceClass.MessageProcessing ("Client begin to connect to"+ipTargetPoint);
         ///////////////////////////////////////
         // Connect to a remote device.
         try {
        	    	// Connect to the remote endpoint.
                 MySocket.BeginConnect(ipTargetPoint,new AsyncCallback(ConnectCallback), MySocket);
             }
         catch (Exception e)
             {
                 SentDoneFlag = true;
                 Debug.Log (e.ToString());
             }
     return 0;
 }
예제 #23
0
파일: Network.cs 프로젝트: hhrhzy/mywork
 public void Connect(string ip, int port ,int timeout)
 {
     socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     try
     {
         socket.BeginConnect(new IPEndPoint(IPAddress.Parse(ip), port), new AsyncCallback(ConnectCallBack), socket);
         Timer_Do = new System.Timers.Timer(timeout);
         Timer_Do.AutoReset = true;
         Timer_Do.Elapsed += new System.Timers.ElapsedEventHandler(Timer_ToDo);
         Timer_Do.Enabled = true;
     }
     catch
     {
         if (OnInvalidIP != null)
         {
             OnInvalidIP();
         }
     }
 }
예제 #24
0
    public void connect(string ip, int port = 339, int TimeOut = 5000)
    {
        try
        {
            // Close the socket if it is still open
            if (m_sock != null && m_sock.Connected)
            {
                m_sock.Shutdown(SocketShutdown.Both);
                if (this.DisconnectEvent != null)
                {
                    this.DisconnectEvent(this, new EventArgs());
                }
                System.Threading.Thread.Sleep(10);
                m_sock.Close();

            }
            m_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint epServer = new IPEndPoint(IPAddress.Parse(ip), port);
            m_sock.Blocking = false;
            AsyncCallback onconnect = new AsyncCallback(OnConnect);
            IAsyncResult result = m_sock.BeginConnect(epServer, onconnect, m_sock);
            bool success = result.AsyncWaitHandle.WaitOne(TimeOut, true);
            if (!success)
            {
                m_sock.Close();
                if (this.ConnectErrEvent != null)
                {
                    this.ConnectErrEvent(this, new EventArgs());
                }
            }
        }
        catch (Exception)
        {
            if (ConnectErrEvent != null)
            {
                ConnectErrEvent(this, new EventArgs());
            }
        }
        this.ip = ip;
    }
    private static void StartClient()
    {
        // Connect to a remote device.
        try
        {
            // Establish the remote endpoint for the socket.
            // The name of the 
            // remote device is "host.contoso.com".
            //IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
            //IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("129.241.187.44"), 34933);

            // Create a TCP/IP socket.
            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            Console.WriteLine("Created a TCP/IP socket.");
            // Connect to the remote endpoint.
            client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
            connectDone.WaitOne();
            Console.WriteLine("Connected to the remote endpoint.");
            // Send test data to the remote device.
            Send(client, "Connect to: 129.241.187.40:20004\0");
            sendDone.WaitOne();

            // Receive the response from the remote device.
            Receive(client);
            receiveDone.WaitOne();

            // Write the response to the console.
            Console.WriteLine("Response received : {0}", response);

            // Release the socket.
            client.Shutdown(SocketShutdown.Both);
            client.Close();

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
예제 #26
0
    private static void StartClient()
    {
        // Connect to a remote device.
        try
        {
            // Establish the remote endpoint for the socket.
            // The name of the 

            IPAddress ipAddress = ownServerIP;
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

            // Create a TCP/IP socket.
            Client = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);

            // Connect to the remote endpoint.
            Client.BeginConnect(remoteEP,
                new AsyncCallback(ConnectCallback), Client);
            connectDone.WaitOne();

            // Send test data to the remote device.
            Send(Client, "next_server");
            sendDone.WaitOne();

            // Receive the response from the remote device.
            Receive(Client);
            receiveDone.WaitOne();

            // Write the response to the console.
            Console.WriteLine("Response received : {0}", response);
            recivedIP = IPAddress.Parse("169.254.80.80");//IPAddress.Parse(response);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
예제 #27
0
    // 连接服务器
    public bool Connect(string address, int remotePort)
    {
        if (_socket != null && _socket.Connected)
            return true;

        try
        {
            IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(address), remotePort);

            // 创建socket
            _socket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            // 开始连接
            _socket.BeginConnect(ipe, new System.AsyncCallback(ConnectionCallback), _socket);
        }
        catch (System.Exception e)
        {
            // 连接失败
            PushPacket((ushort)MessageIdentifiers.ID.CONNECTION_ATTEMPT_FAILED, e.Message);
            return false;
        }

        return true;
    }
예제 #28
0
    public Boolean ConnectToServer(string strIpAddr, UInt16 sPort)
    {
        IPAddress ipAddress = IPAddress.Parse(strIpAddr);

        IPEndPoint ipEndpoint = new IPEndPoint(ipAddress, sPort);

        m_ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        m_ClientSocket.SendTimeout = mTimeOut;

        try
        {
            // ����һ���첽�Ľ������ӣ������ӽ����ɹ�ʱ����connectCallback����
            m_ClientSocket.BeginConnect(ipEndpoint, new AsyncCallback(ConnectCallBack), m_ClientSocket);
        }
        catch (System.Exception ex)
        {
            Debug.Print("Connect Exception: " + ex.Message);
        }

        SetConnectState(ConnectState.Start_Connect);

        return true;
    }
예제 #29
0
파일: Socket.cs 프로젝트: TowerSay/Tower
	public virtual void Connect()
	{
		if(clientSocket!=null && clientSocket.Connected)return ;

		//创建Socket对象
		clientSocket = new Socket (AddressFamily.InterNetwork,socketType,protocolType);
		//服务器IP地址
		IPAddress ipAddress = IPAddress.Parse (ip);
		//服务器端口
		IPEndPoint ipEndpoint = new IPEndPoint (ipAddress,point);
		//这是一个异步的建立连接,当连接建立成功时调用connectCallback方法
		IAsyncResult result = clientSocket.BeginConnect (ipEndpoint,new AsyncCallback (connectCallback),clientSocket);

		//这里做一个超时的监测,当连接超过5秒还没成功表示超时
		bool success = result.AsyncWaitHandle.WaitOne( 5000, true );

		
		if ( !success )
		{
			//超时
			Closed();
			Debug.Log("连接超时!");
		}
		else
		{
			Debug.Log("与socket建立连接成功");
			//与socket建立连接成功,开启线程接受服务端数据。
			//worldpackage = new List<JFPackage.WorldPackage>();
			thread = new Thread(new ThreadStart(ReceiveSorket));
			thread.IsBackground = true;
			thread.Start();
		}



	}
    public void Connect()
	{
        try
        {
            m_NetworkState = NetworkState.Identifying;

            m_ClientSocket = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream,
                ProtocolType.Tcp);

            m_ClientSocket.BeginConnect(new IPEndPoint(IPAddress.Parse(k_ServerHostName),
                k_ServerPort),
                new AsyncCallback(ConnectCallback), 
                null);
        }
        catch (Exception ex)
        {
            Debug.LogError(ex.Message);
            if (OnNetworkError != null)
                OnNetworkError(ex.Message);

            Connect();
        }
    }
예제 #31
0
        public void Scan()
        {
            int StartPort = Convert.ToInt32(portsTo.Value);
            int EndPort = Convert.ToInt32(portsFrom.Value);
            int i, j = 0;

            if (isScanAllPorts.Checked)
            {
                StartPort = 1;
                EndPort   = 9999;
            }

            if (EndPort < StartPort)
            {
                int buffer = StartPort;
                StartPort = EndPort;
                EndPort   = buffer;
            }

            this.Invoke(new Action(delegate
            {
                progress_bar.Maximum = EndPort - StartPort + 1;
                progress_bar.Value   = 0;
                listview_scanner.Items.Clear();
            }));

            IPAddress IpAddr = IPAddress.Parse(hostBox.Text);

            for (i = StartPort; i <= EndPort; i++)
            {
                //Создаем сокет
                IPEndPoint IpEndP = new IPEndPoint(IpAddr, i);
                Socket     MySoc  = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //Пробуем подключится к указанному хосту
                IAsyncResult asyncResult = MySoc.BeginConnect(IpEndP, new AsyncCallback(ConnectCallback), MySoc);

                if (!asyncResult.AsyncWaitHandle.WaitOne(30, false))
                {
                    MySoc.Close();
                    this.Invoke(new Action(delegate
                    {
                        progress_bar.Value += 1;
                        if (isJustOpenPorts.Checked)
                        {
                            return;
                        }
                        listview_scanner.Items.Add("Порт " + i.ToString());
                        listview_scanner.Items[j].SubItems.Add("закрыт");
                        listview_scanner.Items[j].BackColor = Color.Bisque;
                        j++;
                    }));
                }
                else
                {
                    MySoc.Close();
                    this.Invoke(new Action(delegate
                    {
                        progress_bar.Value += 1;
                        listview_scanner.Items.Add("Порт " + i.ToString());
                        listview_scanner.Items[j].SubItems.Add("открыт");
                        listview_scanner.Items[j].BackColor = Color.LightGreen;
                        j++;
                    }));
                }
            }

            this.Invoke(new Action(delegate
            {
                progress_bar.Value = 0;
                scan_button.Text   = "Сканировать";
                isStart            = false;
            }));
        }
예제 #32
0
        public static string GetInfo(string ip, int port)
        {
            Console.OutputEncoding = System.Text.Encoding.UTF8;
            int    timeout    = 5000; // ms
            string bannerText = "";

            Byte[] buffer = new Byte[512];
            using (Socket telnetSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                telnetSocket.ReceiveTimeout = timeout;
                telnetSocket.SendTimeout    = timeout;
                try
                {
                    var  result  = telnetSocket.BeginConnect(ip, port, null, null);
                    bool success = result.AsyncWaitHandle.WaitOne(timeout, true);
                    if (success)
                    {
                        // Back and forth handshakes for some reason - I have no idea...
                        // Receive 1 - And Parrot
                        int bytes = telnetSocket.Receive(buffer, buffer.Length, 0);
                        if (buffer[0] == 255 && buffer[1] == 253 && buffer[2] == 24)
                        {
                            telnetSocket.Send(buffer, bytes, 0);
                            // Receive 2 - And Parrot
                            bytes = telnetSocket.Receive(buffer, buffer.Length, 0);
                            telnetSocket.Send(buffer, bytes, 0);
                            // Receive 3 - And Parrot
                            bytes = telnetSocket.Receive(buffer, buffer.Length, 0);
                            telnetSocket.Send(buffer, bytes, 0);
                            // Receive 4 - And Parrot
                            bytes = telnetSocket.Receive(buffer, buffer.Length, 0);
                            telnetSocket.Send(buffer, bytes, 0);
                            // Receive 5 - And Parrot
                            bytes = telnetSocket.Receive(buffer, buffer.Length, 0);
                            telnetSocket.Send(buffer, bytes, 0);
                            // Receive 6 - And this is the one we want
                            bytes = telnetSocket.Receive(buffer, buffer.Length, 0);
                            string response = Encoding.UTF8.GetString(buffer, 0, bytes);
                            if (response.Length > 5)
                            {
                                return("- - - - - - - - - - - - - - - -" + Environment.NewLine + response + Environment.NewLine + "- - - - - - - - - - - - - - - -");
                            }
                            else if (response.Length > 0)
                            {
                                return("- Weird response length: " + response);
                            }
                            else
                            {
                                return("- No Response :<");
                            }
                        }
                        else
                        {
                            return("- Invalid Telnet Response :<");
                        }
                    }
                    bannerText = bannerText.Trim();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error in Telnet.cs: " + ex.Message + " - Bug Reelix");
                }
            }
            return("- :(");
        }
예제 #33
0
 public void Connect()
 {
     clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     clientSocket.BeginConnect(host, port,
                               new AsyncCallback(ConnectCallback), clientSocket);
 }
예제 #34
0
            /// <summary>
            /// 连接到远程主机。
            /// </summary>
            /// <param name="ipAddress">远程主机的 IP 地址。</param>
            /// <param name="port">远程主机的端口号。</param>
            /// <param name="userData">用户自定义数据。</param>
            public void Connect(IPAddress ipAddress, int port, object userData)
            {
                if (m_Socket != null)
                {
                    Close();
                    m_Socket = null;
                }

                switch (ipAddress.AddressFamily)
                {
                case AddressFamily.InterNetwork:
                    m_NetworkType = NetworkType.IPv4;
                    break;

                case AddressFamily.InterNetworkV6:
                    m_NetworkType = NetworkType.IPv6;
                    break;

                default:
                    string errorMessage = Utility.Text.Format("Not supported address family '{0}'.", ipAddress.AddressFamily.ToString());
                    if (NetworkChannelError != null)
                    {
                        NetworkChannelError(this, NetworkErrorCode.AddressFamilyError, SocketError.Success, errorMessage);
                        return;
                    }

                    throw new GameFrameworkException(errorMessage);
                }

                m_Socket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                if (m_Socket == null)
                {
                    string errorMessage = "Initialize network channel failure.";
                    if (NetworkChannelError != null)
                    {
                        NetworkChannelError(this, NetworkErrorCode.SocketError, SocketError.Success, errorMessage);
                        return;
                    }

                    throw new GameFrameworkException(errorMessage);
                }

                m_SendState.Reset();
                m_ReceiveState.PrepareForPacketHeader(m_NetworkChannelHelper.PacketHeaderLength);

                try
                {
                    m_Socket.BeginConnect(ipAddress, port, m_ConnectCallback, new ConnectState(m_Socket, userData));
                }
                catch (Exception exception)
                {
                    if (NetworkChannelError != null)
                    {
                        SocketException socketException = exception as SocketException;
                        NetworkChannelError(this, NetworkErrorCode.ConnectError, socketException != null ? socketException.SocketErrorCode : SocketError.Success, exception.ToString());
                        return;
                    }

                    throw;
                }
            }
예제 #35
0
 void Start()
 {
     socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     socket.BeginConnect(IPAddress.Parse(ip), port, new AsyncCallback(ConnectCallback), null);
 }
예제 #36
0
        public void Connect(string address, int port)
        {
            Audit.WriteLine("Connect " + address + " -- " + port);
            Disconnect();
            mState = State.Waiting;
            //
            // permissions
            SocketPermission mySocketPermission1 = new SocketPermission(PermissionState.None);

            mySocketPermission1.AddPermission(NetworkAccess.Connect, TransportType.All, "localhost", 8800);
            mySocketPermission1.Demand();

            //
            // Actually connect
            //
            // count .s, numeric and 3 .s =ipaddress
            bool ipaddress = false;
            bool text      = false;
            int  count     = 0;
            int  i;

            for (i = 0; i < address.Length; i++)
            {
                if (address[i] == '.')
                {
                    count++;
                }
                else
                {
                    if (address[i] < '0' || address[i] > '9')
                    {
                        text = true;
                    }
                }
            }
            if (count == 3 && text == false)
            {
                ipaddress = true;
            }

            if (!ipaddress)
            {
                Audit.WriteLine("Dns.Resolve " + address);
                IPHostEntry IPHost  = Dns.GetHostEntry(address);
                string []   aliases = IPHost.Aliases;
                IPAddress[] addr    = IPHost.AddressList;
                iep = new IPEndPoint(addr[0], port);
            }
            else
            {
                Audit.WriteLine("Use address " + address + " as ip");
                iep = new IPEndPoint(IPAddress.Parse(address), port);
            }


            try
            {
                // Create New Socket
                mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                // Create New EndPoint
                // This is a non blocking IO
                mSocket.Blocking = false;
                // set some random options
                //
                //mSocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1);

                //
                // Assign Callback function to read from Asyncronous Socket
                callbackProc = new AsyncCallback(ConnectCallback);
                // Begin Asyncronous Connection
                mSocket.BeginConnect(iep, callbackProc, mSocket);
            }
            catch (Exception eeeee)
            {
                Audit.WriteLine("e=" + eeeee);
                throw;
                //				st_changed(STCALLBACK.ST_CONNECT, false);
            }
        }
예제 #37
0
        ///<summary>Processes a specified query and connects to the requested HTTP web server.</summary>
        ///<param name="Query">A string containing the query to process.</param>
        ///<remarks>If there's an error while processing the HTTP request or when connecting to the remote server, the Proxy sends a "400 - Bad Request" error to the client.</remarks>
        protected virtual void ProcessQuery(string Query)
        {
            HeaderFields = ParseQuery(Query);
            if (HeaderFields == null || !HeaderFields.ContainsKey("Host"))
            {
                SendBadRequest();
                return;
            }
            int    Port;
            string Host;
            int    Ret;

            if (HttpRequestType.ToUpper().Equals("CONNECT"))       //HTTPS
            {
                Ret = RequestedPath.IndexOf(":");
                if (Ret >= 0)
                {
                    Host = RequestedPath.Substring(0, Ret);
                    if (RequestedPath.Length > Ret + 1)
                    {
                        Port = int.Parse(RequestedPath.Substring(Ret + 1));
                    }
                    else
                    {
                        Port = 443;
                    }
                }
                else
                {
                    Host = RequestedPath;
                    Port = 443;
                }
            }
            else         //Normal HTTP
            {
                Ret = ((string)HeaderFields["Host"]).IndexOf(":");
                if (Ret > 0)
                {
                    Host = ((string)HeaderFields["Host"]).Substring(0, Ret);
                    Port = int.Parse(((string)HeaderFields["Host"]).Substring(Ret + 1));
                }
                else
                {
                    Host = (string)HeaderFields["Host"];
                    Port = 80;
                }
                if (HttpRequestType.ToUpper().Equals("POST"))
                {
                    int index = Query.IndexOf("\r\n\r\n");
                    m_HttpPost = Query.Substring(index + 4);
                }
            }
            try {
                IPEndPoint DestinationEndPoint = new IPEndPoint(Dns.Resolve(Host).AddressList[0], Port);
                DestinationSocket = new Socket(DestinationEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                if (HeaderFields.ContainsKey("Proxy-Connection") && HeaderFields["Proxy-Connection"].ToLower().Equals("keep-alive"))
                {
                    DestinationSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);
                }
                DestinationSocket.BeginConnect(DestinationEndPoint, new AsyncCallback(this.OnConnected), DestinationSocket);
            } catch {
                SendBadRequest();
                return;
            }
        }
예제 #38
0
    private static void StartClient()
    {
        // Connect to a remote device.
        try
        {
            // Establish the remote endpoint for the socket.
            // The name of the
            // remote device is "host.contoso.com".
            IPHostEntry ipHostInfo = Dns.GetHostEntry("127.0.0.1");
            IPAddress   ipAddress  = ipHostInfo.AddressList[0];
            IPEndPoint  remoteEP   = new IPEndPoint(ipAddress, port);

            // Create a TCP/IP socket.
            Socket client = new Socket(ipAddress.AddressFamily,
                                       SocketType.Stream, ProtocolType.Tcp);

            // Connect to the remote endpoint.
            client.BeginConnect(remoteEP,
                                new AsyncCallback(ConnectCallback), client);
            connectDone.WaitOne();

            bool   flag        = true;
            string commandLine = "";
            Console.WriteLine("Write your command (insert, update or find) followed by first name, last name and date of birth (YYYY/MM/DD).\n" +
                              "Please separate each operation with a single space. Type a single 'quit' to quit the program.\n" +
                              "E.g.: To insert an entry:\"insert John Doe 1956/01/22\"\n" +
                              "to update an entry start with the ID: \"update 34 John Doe 1966/01/22\"");

            while (flag == true)
            {
                commandLine = Console.ReadLine();
                if (commandLine == "quit")
                {
                    flag = false;
                }
                if (commandLine == "help")
                {
                    Console.WriteLine("Write your command (insert, update or find) followed by first name, last name and date of Birth.\n" +
                                      "(Please separate each operation with a single space. Type a single '0' to exit.)");
                    continue;
                }

                // Send data to the remote device.
                Send(client, commandLine);
                sendDone.WaitOne();

                // Receive the response from the remote device.
                Receive(client);
                receiveDone.WaitOne();

                // Write the response to the console.
                Console.WriteLine("Response received : {0}", response);
            }

            // Release the socket.
            client.Shutdown(SocketShutdown.Both);
            client.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
예제 #39
0
        public void Configure(IApplicationBuilder app, IHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async(context) =>
            {
                await Task.Run(() =>
                {
                    if (context.Request.Path == "/connectivity/")
                    {
                        if (!ushort.TryParse(context.Request.Query["port"], out ushort port))
                        {
                            context.Response.StatusCode = 400;
                            return;
                        }

                        IPEndPoint remoteEP = new IPEndPoint(GetRequestRemoteAddress(context), port);
                        bool success        = false;

                        try
                        {
                            using (Socket socket = new Socket(remoteEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
                            {
                                IAsyncResult result = socket.BeginConnect(remoteEP, null, null);
                                if (!result.AsyncWaitHandle.WaitOne(CONNECTION_TIMEOUT))
                                {
                                    throw new SocketException((int)SocketError.TimedOut);
                                }

                                socket.NoDelay        = true;
                                socket.SendTimeout    = SOCKET_SEND_TIMEOUT;
                                socket.ReceiveTimeout = SOCKET_RECV_TIMEOUT;

                                MakeDecoyHttpConnection(new NetworkStream(socket), remoteEP);

                                success = true;
                            }
                        }
                        catch
                        { }

                        List <IPEndPoint> peerEPs = new List <IPEndPoint>();
                        bool add;

                        _openPeerEPsLock.EnterReadLock();
                        try
                        {
                            add = (_openPeerEPs.Count < MAX_PEER_ENDPOINTS);

                            foreach (PeerEndPoint peerEP in _openPeerEPs)
                            {
                                if (remoteEP.Equals(peerEP.EndPoint))
                                {
                                    add = false;

                                    if (success)
                                    {
                                        peerEP.AddedOn = DateTime.UtcNow;
                                    }
                                }
                                else
                                {
                                    peerEPs.Add(peerEP.EndPoint);
                                }
                            }
                        }
                        finally
                        {
                            _openPeerEPsLock.ExitReadLock();
                        }

                        if (add)
                        {
                            _openPeerEPsLock.EnterWriteLock();
                            try
                            {
                                if (_openPeerEPs.Count < MAX_PEER_ENDPOINTS)
                                {
                                    _openPeerEPs.Add(new PeerEndPoint(remoteEP));
                                }
                            }
                            finally
                            {
                                _openPeerEPsLock.ExitWriteLock();
                            }
                        }

                        context.Response.ContentType = "application/octet-stream";

                        using (MemoryStream mS = new MemoryStream(20))
                        {
                            BinaryWriter bW = new BinaryWriter(mS);

                            bW.Write((byte)1);    //version
                            bW.Write(success);    //test status
                            remoteEP.WriteTo(bW); //self end-point

                            //write peers
                            bW.Write(Convert.ToByte(peerEPs.Count));
                            foreach (IPEndPoint peerEP in peerEPs)
                            {
                                peerEP.WriteTo(bW);
                            }

                            byte[] output = mS.ToArray();

                            context.Response.Headers.Add("Content-Length", output.Length.ToString());

                            using (context.Response.Body)
                            {
                                context.Response.Body.WriteAsync(output, 0, output.Length);
                            }
                        }
                    }
                    else
                    {
                        context.Response.StatusCode = 404;
                    }
                });
            });
        }
예제 #40
0
        internal static Dictionary <Authority, bool> CheckConnectivity(IAutoProvision[] clients, AutoProvisionProgress provisionProgressCallback)
        {
            Dictionary <string, IPAddress[]> dictionary = new Dictionary <string, IPAddress[]>(StringComparer.OrdinalIgnoreCase);

            foreach (IAutoProvision autoProvision in clients)
            {
                foreach (string text in autoProvision.Hostnames)
                {
                    if (!dictionary.ContainsKey(text))
                    {
                        if (text.Length > SyncUtilities.MaximumFqdnLength)
                        {
                            CommonLoggingHelper.SyncLogSession.LogError((TSLID)1265UL, "FQDN: [{0}] with length: {1} was too long.", new object[]
                            {
                                text,
                                text.Length
                            });
                            dictionary.Add(text, null);
                        }
                        else
                        {
                            try
                            {
                                provisionProgressCallback(Strings.AutoProvisionQueryDNS, new LocalizedString(text));
                                CommonLoggingHelper.SyncLogSession.LogInformation((TSLID)1266UL, "Querying DNS: {0}", new object[]
                                {
                                    text
                                });
                                IPHostEntry hostEntry = Dns.GetHostEntry(text);
                                dictionary.Add(text, hostEntry.AddressList);
                            }
                            catch (SocketException ex)
                            {
                                CommonLoggingHelper.SyncLogSession.LogError((TSLID)1267UL, "DNS Query failed with error: {0}", new object[]
                                {
                                    ex
                                });
                                dictionary.Add(text, null);
                            }
                        }
                    }
                }
            }
            Dictionary <Authority, bool>   dictionary2 = new Dictionary <Authority, bool>();
            Dictionary <Socket, Authority> dictionary3 = new Dictionary <Socket, Authority>();

            try
            {
                List <IAsyncResult> list  = new List <IAsyncResult>();
                List <WaitHandle>   list2 = new List <WaitHandle>();
                foreach (IAutoProvision autoProvision2 in clients)
                {
                    foreach (string text2 in autoProvision2.Hostnames)
                    {
                        foreach (int num in autoProvision2.ConnectivePorts)
                        {
                            Authority authority = new Authority(text2, num);
                            if (!dictionary2.ContainsKey(authority))
                            {
                                dictionary2[authority] = false;
                                if (dictionary[text2] == null)
                                {
                                    CommonLoggingHelper.SyncLogSession.LogInformation((TSLID)1268UL, "No valid DNS results exist for fqdn: {0}", new object[]
                                    {
                                        text2
                                    });
                                }
                                else
                                {
                                    provisionProgressCallback(Strings.AutoProvisionConnectivity, new LocalizedString(authority.ToString()));
                                    CommonLoggingHelper.SyncLogSession.LogInformation((TSLID)1269UL, "Connecting to {0} ...", new object[]
                                    {
                                        authority
                                    });
                                    Socket       socket      = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                                    IAsyncResult asyncResult = null;
                                    try
                                    {
                                        asyncResult = socket.BeginConnect(dictionary[text2], num, null, socket);
                                    }
                                    catch (SocketException)
                                    {
                                        socket.Close();
                                        goto IL_284;
                                    }
                                    dictionary3.Add(socket, authority);
                                    list.Add(asyncResult);
                                    list2.Add(asyncResult.AsyncWaitHandle);
                                }
                            }
                            IL_284 :;
                        }
                    }
                }
                if (list2.Count == 0)
                {
                    return(dictionary2);
                }
                provisionProgressCallback(Strings.AutoProvisionConnectivity, Strings.AutoProvisionResults);
                WaitHandle.WaitAll(list2.ToArray(), NewSubscription.socketTimeout, false);
                foreach (IAsyncResult asyncResult2 in list)
                {
                    if (asyncResult2.IsCompleted)
                    {
                        Socket socket2 = (Socket)asyncResult2.AsyncState;
                        try
                        {
                            socket2.EndConnect(asyncResult2);
                        }
                        catch (SocketException)
                        {
                        }
                    }
                }
            }
            finally
            {
                foreach (KeyValuePair <Socket, Authority> keyValuePair in dictionary3)
                {
                    Socket    key   = keyValuePair.Key;
                    Authority value = keyValuePair.Value;
                    if (key.Connected)
                    {
                        dictionary2[value] = true;
                    }
                    CommonLoggingHelper.SyncLogSession.LogInformation((TSLID)1270UL, "Connection to {0} succeeded: {1}.", new object[]
                    {
                        value,
                        key.Connected
                    });
                    key.Close();
                }
            }
            return(dictionary2);
        }
        private void Connect()
        {
            if (UsageTimer == null)
            {
                //Save Timer Resource for licensed usage
                if (!LicenseUtils.HasLicensedFeature(LicenseFeature.Redis))
                {
                    UsageTimer = new Timer(delegate
                    {
                        __requestsPerHour = 0;
                    }, null, TimeSpan.FromMilliseconds(0), TimeSpan.FromHours(1));
                }
            }

            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            {
                SendTimeout    = SendTimeout,
                ReceiveTimeout = ReceiveTimeout
            };
            try
            {
                if (ConnectTimeout <= 0)
                {
                    socket.Connect(Host, Port);
                }
                else
                {
                    var connectResult = socket.BeginConnect(Host, Port, null, null);
                    connectResult.AsyncWaitHandle.WaitOne(ConnectTimeout, true);
                }

                if (!socket.Connected)
                {
                    socket.Close();
                    socket        = null;
                    DeactivatedAt = DateTime.UtcNow;
                    return;
                }

                Stream networkStream = new NetworkStream(socket);

                if (Ssl)
                {
                    if (Env.IsMono)
                    {
                        //Mono doesn't support EncryptionPolicy
                        sslStream = new SslStream(networkStream,
                                                  leaveInnerStreamOpen: false,
                                                  userCertificateValidationCallback: RedisConfig.CertificateValidationCallback,
                                                  userCertificateSelectionCallback: RedisConfig.CertificateSelectionCallback);
                    }
                    else
                    {
                        var ctor = typeof(SslStream).GetConstructors()
                                   .First(x => x.GetParameters().Length == 5);

                        var policyType  = AssemblyUtils.FindType("System.Net.Security.EncryptionPolicy");
                        var policyValue = Enum.Parse(policyType, "RequireEncryption");

                        sslStream = (SslStream)ctor.Invoke(new[] {
                            networkStream,
                            false,
                            RedisConfig.CertificateValidationCallback,
                            RedisConfig.CertificateSelectionCallback,
                            policyValue,
                        });
                    }

                    sslStream.AuthenticateAsClient(Host);

                    if (!sslStream.IsEncrypted)
                    {
                        throw new Exception("Could not establish an encrypted connection to " + Host);
                    }

                    networkStream = sslStream;
                }

                Bstream = new BufferedStream(networkStream, 16 * 1024);

                if (!string.IsNullOrEmpty(Password))
                {
                    SendUnmanagedExpectSuccess(Commands.Auth, Password.ToUtf8Bytes());
                }

                if (db != 0)
                {
                    SendUnmanagedExpectSuccess(Commands.Select, db.ToUtf8Bytes());
                }

                if (Client != null)
                {
                    SendUnmanagedExpectSuccess(Commands.Client, Commands.SetName, Client.ToUtf8Bytes());
                }

                try
                {
                    if (ServerVersionNumber == 0)
                    {
                        ServerVersionNumber = RedisConfig.AssumeServerVersion.GetValueOrDefault(0);
                        if (ServerVersionNumber <= 0)
                        {
                            var parts   = ServerVersion.Split('.');
                            var version = int.Parse(parts[0]) * 1000;
                            if (parts.Length > 1)
                            {
                                version += int.Parse(parts[1]) * 100;
                            }
                            if (parts.Length > 2)
                            {
                                version += int.Parse(parts[2]);
                            }

                            ServerVersionNumber = version;
                        }
                    }
                }
                catch (Exception)
                {
                    //Twemproxy doesn't support the INFO command so automatically closes the socket
                    //Fallback to ServerVersionNumber=Unknown then try re-connecting
                    ServerVersionNumber = Unknown;
                    Connect();
                    return;
                }

                var ipEndpoint = socket.LocalEndPoint as IPEndPoint;
                clientPort               = ipEndpoint != null ? ipEndpoint.Port : -1;
                lastCommand              = null;
                lastSocketException      = null;
                LastConnectedAtTimestamp = Stopwatch.GetTimestamp();

                OnConnected();

                if (ConnectionFilter != null)
                {
                    ConnectionFilter(this);
                }
            }
            catch (SocketException)
            {
                log.Error(ErrorConnect.Fmt(Host, Port));
                throw;
            }
        }
예제 #42
0
        public TdsComm(string dataSource, int port, int packetSize, int timeout, TdsVersion tdsVersion)
        {
            this.packetSize = packetSize;
            this.tdsVersion = tdsVersion;
            this.dataSource = dataSource;

            outBuffer = new byte[packetSize];
            inBuffer  = new byte[packetSize];

            outBufferLength = packetSize;
            inBufferLength  = packetSize;

            lsb = true;

            IPEndPoint endPoint;
            bool       have_exception = false;

            try {
#if NET_2_0
                IPAddress ip;
                if (IPAddress.TryParse(this.dataSource, out ip))
                {
                    endPoint = new IPEndPoint(ip, port);
                }
                else
                {
                    IPHostEntry hostEntry = Dns.GetHostEntry(this.dataSource);
                    endPoint = new IPEndPoint(hostEntry.AddressList [0], port);
                }
#else
                IPHostEntry hostEntry = Dns.Resolve(this.dataSource);
                endPoint = new IPEndPoint(hostEntry.AddressList [0], port);
#endif
            } catch (SocketException e) {
                throw new TdsInternalException("Server does not exist or connection refused.", e);
            }

            try {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IAsyncResult ares       = socket.BeginConnect(endPoint, null, null);
                int          timeout_ms = timeout * 1000;
                if (timeout > 0 && !ares.IsCompleted && !ares.AsyncWaitHandle.WaitOne(timeout_ms, false))
                {
                    throw Tds.CreateTimeoutException(dataSource, "Open()");
                }
                socket.EndConnect(ares);
                try {
                    // MS sets these socket option
                    socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);
                } catch (SocketException) {
                    // Some platform may throw an exception, so
                    // eat all socket exception, yeaowww!
                }

                try {
#if NET_2_0
                    socket.NoDelay = true;
#endif
                    socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout_ms);
                    socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout_ms);
                } catch {
                    // Ignore exceptions here for systems that do not support these options.
                }
                // Let the stream own the socket and take the pleasure of closing it
                stream = new NetworkStream(socket, true);
            } catch (SocketException e) {
                have_exception = true;
                throw new TdsInternalException("Server does not exist or connection refused.", e);
            } catch (Exception) {
                have_exception = true;
                throw;
            } finally {
                if (have_exception && socket != null)
                {
                    try {
                        Socket s = socket;
                        socket = null;
                        s.Close();
                    } catch {}
                }
            }
            if (!socket.Connected)
            {
                throw new TdsInternalException("Server does not exist or connection refused.", null);
            }
            packetsSent = 1;
        }
예제 #43
0
        private PipelineInstruction QueueOrCreateDataConection(PipelineEntry entry, ResponseDescription response, bool timeout, ref Stream stream, out bool isSocketReady)
        {
            isSocketReady = false;
            if (_dataHandshakeStarted)
            {
                isSocketReady = true;
                return(PipelineInstruction.Pause); //if we already started then this is re-entering into the callback where we proceed with the stream
            }

            _dataHandshakeStarted = true;

            // Handle passive responses by parsing the port and later doing a Connect(...)
            bool isPassive = false;
            int  port      = -1;

            if (entry.Command == "PASV\r\n" || entry.Command == "EPSV\r\n")
            {
                if (!response.PositiveCompletion)
                {
                    _abortReason = SR.Format(SR.net_ftp_server_failed_passive, response.Status);
                    return(PipelineInstruction.Abort);
                }
                if (entry.Command == "PASV\r\n")
                {
                    port = GetPortV4(response.StatusDescription);
                }
                else
                {
                    port = GetPortV6(response.StatusDescription);
                }

                isPassive = true;
            }

            if (isPassive)
            {
                if (port == -1)
                {
                    NetEventSource.Fail(this, "'port' not set.");
                }

                try
                {
                    _dataSocket = CreateFtpDataSocket((FtpWebRequest)_request, Socket);
                }
                catch (ObjectDisposedException)
                {
                    throw ExceptionHelper.RequestAbortedException;
                }

                IPEndPoint localEndPoint = new IPEndPoint(((IPEndPoint)Socket.LocalEndPoint).Address, 0);
                _dataSocket.Bind(localEndPoint);

                _passiveEndPoint = new IPEndPoint(ServerAddress, port);
            }

            PipelineInstruction result;

            if (_passiveEndPoint != null)
            {
                IPEndPoint passiveEndPoint = _passiveEndPoint;
                _passiveEndPoint = null;
                if (NetEventSource.IsEnabled)
                {
                    NetEventSource.Info(this, "starting Connect()");
                }
                if (_isAsync)
                {
                    _dataSocket.BeginConnect(passiveEndPoint, s_connectCallbackDelegate, this);
                    result = PipelineInstruction.Pause;
                }
                else
                {
                    _dataSocket.Connect(passiveEndPoint);
                    result = PipelineInstruction.Advance; // for passive mode we end up going to the next command
                }
            }
            else
            {
                if (NetEventSource.IsEnabled)
                {
                    NetEventSource.Info(this, "starting Accept()");
                }

                if (_isAsync)
                {
                    _dataSocket.BeginAccept(s_acceptCallbackDelegate, this);
                    result = PipelineInstruction.Pause;
                }
                else
                {
                    Socket listenSocket = _dataSocket;
                    try
                    {
                        _dataSocket = _dataSocket.Accept();
                        if (!ServerAddress.Equals(((IPEndPoint)_dataSocket.RemoteEndPoint).Address))
                        {
                            _dataSocket.Close();
                            throw new WebException(SR.net_ftp_active_address_different, WebExceptionStatus.ProtocolError);
                        }
                        isSocketReady = true;   // for active mode we end up creating a stream before advancing the pipeline
                        result        = PipelineInstruction.Pause;
                    }
                    finally
                    {
                        listenSocket.Close();
                    }
                }
            }
            return(result);
        }
예제 #44
0
파일: Server.cs 프로젝트: xuxx09/resin
        private HmuxConnection Connect()
        {
            lock (this) {
                if (_maxConnections <= _activeCount + _startingCount)
                {
                    return(null);
                }

                _startingCount++;
            }

            HmuxConnection connection = null;

            Object connectLock = new Object();

            Monitor.Enter(connectLock);
            try {
                Socket socket = new Socket(_address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                AsyncCallback connectListener = delegate(IAsyncResult result)
                {
                    Monitor.Enter(connectLock);
                    try {
                        Monitor.Pulse(connectLock);
                    } catch (Exception) {
                    } finally {
                        Monitor.Exit(connectLock);
                    }
                };

                socket.BeginConnect(_address, _port, connectListener, socket);
                Monitor.Wait(connectLock, _loadBalanceConnectTimeout);

                if (!socket.Connected)
                {
                    throw new SocketException(10053);
                }

                socket.SendTimeout    = _socketTimeout;
                socket.ReceiveTimeout = _socketTimeout;

                String traceId;
                if (_isDebug)
                {
                    int i = _traceId++;
                    traceId = i.ToString();
                }
                else
                {
                    traceId = socket.Handle.ToInt32().ToString();
                }

                connection = new HmuxConnection(socket, this, _serverInternalId, traceId);

                lock (this) {
                    _activeCount++;
                }

                if (_log.IsLoggable(EventLogEntryType.Information))
                {
                    _log.Info("Connect " + connection);
                }

                Trace.TraceInformation("Connect '{0}'", connection);

                return(connection);
            } catch (SocketException e) {
                String message = String.Format("Socket connection to {0}:{1} timed out on load-balance-connect-timeout {2}", _address, _port, _loadBalanceConnectTimeout);
                if (_log.IsLoggable(EventLogEntryType.Information))
                {
                    _log.Info(message);
                }

                Trace.TraceInformation(message);
            } catch (Exception e) {
                String message = String.Format("Can't create HmuxChannel to '{0}:{1}' due to: {2} \t {3}", _address, _port, e.Message, e.StackTrace);
                if (_log.IsLoggable(EventLogEntryType.Information))
                {
                    _log.Info(message);
                }

                Trace.TraceError(message);
            } finally {
                lock (this) {
                    _startingCount--;
                }

                if (connection == null)
                {
                    FailConnect();
                }

                Monitor.Exit(connectLock);
            }

            return(null);
        }
예제 #45
0
        /// <summary>
        /// Prints a test label.
        /// </summary>
        protected void SendTestPrint()
        {
            if (CurrentKioskId != null)
            {
                // get the current kiosk print options
                Device device = null;
                if (CurrentCheckInState != null)
                {
                    device = CurrentCheckInState.Kiosk.Device;
                }

                // get the current device and printer
                if (device == null || device.PrinterDevice == null)
                {
                    using (var rockContext = new RockContext())
                    {
                        var deviceService = new DeviceService(rockContext);
                        device = device ?? deviceService.Get((int)CurrentKioskId);
                        device.PrinterDevice = device.PrinterDevice ?? deviceService.Get((int)device.PrinterDeviceId);
                    }
                }

                var printerAddress = string.Empty;
                if (device != null && device.PrinterDevice != null)
                {
                    printerAddress = device.PrinterDevice.IPAddress;
                }

                // set the label content
                var labelContent = GetAttributeValue("TestLabelContent");
                labelContent = Regex.Replace(labelContent, string.Format(@"(?<=\^FD){0}(?=\^FS)", "DeviceName"), device.Name);
                labelContent = Regex.Replace(labelContent, string.Format(@"(?<=\^FD){0}(?=\^FS)", "PrinterIP"), printerAddress);
                labelContent = Regex.Replace(labelContent, string.Format(@"(?<=\^FD){0}(?=\^FS)", "Date"), RockDateTime.Now.ToString("MM/dd/yy HH:mm tt"));

                // try printing the label
                if (!string.IsNullOrWhiteSpace(labelContent) && !string.IsNullOrWhiteSpace(printerAddress))
                {
                    var  socket            = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    var  printerIpEndPoint = new IPEndPoint(IPAddress.Parse(printerAddress), 9100);
                    var  result            = socket.BeginConnect(printerIpEndPoint, null, null);
                    bool success           = result.AsyncWaitHandle.WaitOne(5000, true);

                    if (socket.Connected)
                    {
                        var    ns     = new NetworkStream(socket);
                        byte[] toSend = System.Text.Encoding.ASCII.GetBytes(labelContent.ToString());
                        ns.Write(toSend, 0, toSend.Length);
                    }
                    else
                    {
                        maAlert.Show(string.Format("Can't connect to printer {0} from {1}", printerAddress, device.Name), ModalAlertType.Alert);
                        pnlContent.Update();
                    }

                    if (socket != null && socket.Connected)
                    {
                        socket.Shutdown(SocketShutdown.Both);
                        socket.Close();
                    }

                    maAlert.Show(string.Format("Sent a test print job to {0} from {1}", printerAddress, device.Name), ModalAlertType.Information);
                    pnlContent.Update();
                }
                else
                {
                    maAlert.Show("The test label or the device printer isn't configured with an IP address.", ModalAlertType.Alert);
                    pnlContent.Update();
                }
            }
            else
            {
                maAlert.Show("Current check-in state is not instantiated.", ModalAlertType.Alert);
                pnlContent.Update();
            }
        }
예제 #46
0
        internal CassandraConnection(Session owner, IPAddress serverAddress, ProtocolOptions protocolOptions,
                                     SocketOptions socketOptions, ClientOptions clientOptions,
                                     IAuthProvider authProvider,
                                     IAuthInfoProvider authInfoProvider)
        {
            this.Guid      = Guid.NewGuid();
            this._owner    = owner;
            _bufferingMode = null;
            switch (protocolOptions.Compression)
            {
            case CompressionType.Snappy:
                _bufferingMode = new FrameBuffering();
                break;

            case CompressionType.NoCompression:
                _bufferingMode = clientOptions.WithoutRowSetBuffering ? new NoBuffering() : new FrameBuffering();
                break;

            default:
                throw new ArgumentException();
            }

            this._authProvider     = authProvider;
            this._authInfoProvider = authInfoProvider;
            if (protocolOptions.Compression == CompressionType.Snappy)
            {
                _startupOptions.Add("COMPRESSION", "snappy");
                _compressor = new SnappyProtoBufCompressor();
            }
            this._serverAddress     = serverAddress;
            this._port              = protocolOptions.Port;
            this._queryAbortTimeout = clientOptions.QueryAbortTimeout;

            this._socketOptions = socketOptions;

            for (int i = 0; i <= sbyte.MaxValue; i++)
            {
                _freeStreamIDs.Push(i);
            }

            _protocolErrorHandlerAction = new Action <ErrorActionParam>((param) =>
            {
                if (param.AbstractResponse is ErrorResponse)
                {
                    JobFinished(
                        param.Jar,
                        (param.AbstractResponse as ErrorResponse).Output);
                }
            });

            _frameEventCallback.Value = new Action <ResponseFrame>(EventOccured);

            _buffer = new byte[][] {
                new byte[_bufferingMode.PreferedBufferSize()],
                new byte[_bufferingMode.PreferedBufferSize()]
            };

            var newSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            if (_socketOptions.KeepAlive != null)
            {
                newSock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive,
                                        _socketOptions.KeepAlive.Value);
            }

            newSock.SendTimeout = _socketOptions.ConnectTimeoutMillis;

            if (_socketOptions.SoLinger != null)
            {
                newSock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger,
                                        new LingerOption(true, _socketOptions.SoLinger.Value));
            }

            if (_socketOptions.ReceiveBufferSize != null)
            {
                newSock.ReceiveBufferSize = _socketOptions.ReceiveBufferSize.Value;
            }

            if (_socketOptions.SendBufferSize != null)
            {
                newSock.ReceiveBufferSize = _socketOptions.SendBufferSize.Value;
            }

            if (_socketOptions.TcpNoDelay != null)
            {
                newSock.NoDelay = _socketOptions.TcpNoDelay.Value;
            }

            //Avoid waiting more time that expected
            var connectionResult = newSock.BeginConnect(_serverAddress, _port, null, null);

            connectionResult.AsyncWaitHandle.WaitOne(_socketOptions.ConnectTimeoutMillis);

            if (!newSock.Connected)
            {
                newSock.Close();
                throw new SocketException((int)SocketError.TimedOut);
            }

            _socket = newSock;
            _bufferingMode.Reset();

            if (protocolOptions.SslOptions == null)
            {
                _socketStream = new NetworkStream(_socket);
            }
            else
            {
                string targetHost;
                try
                {
                    targetHost = Dns.GetHostEntry(_serverAddress).HostName;
                }
                catch (SocketException ex)
                {
                    targetHost = serverAddress.ToString();
                    _logger.Error(string.Format("SSL connection: Can not resolve {0} address. Using IP address instead of hostname. This may cause RemoteCertificateNameMismatch error during Cassandra host authentication. Note that Cassandra node SSL certificate's CN(Common Name) must match the Cassandra node hostname.", _serverAddress.ToString()), ex);
                }

                _socketStream = new SslStream(new NetworkStream(_socket), false, new RemoteCertificateValidationCallback(protocolOptions.SslOptions.RemoteCertValidationCallback), null);
                (_socketStream as SslStream).AuthenticateAsClient(targetHost, new X509CertificateCollection(), protocolOptions.SslOptions.SslProtocol, false);
            }

            if (IsHealthy)
            {
                BeginReading();
            }
        }
예제 #47
0
 public static async Task ConnectAsync(this Socket socket, IPEndPoint endpoint)
 {
     await Task.Factory.FromAsync((callback, state) => socket.BeginConnect(endpoint, callback, state), ias => socket.EndConnect(ias), null);
 }
예제 #48
0
        public void PingIt(string[] args)
        {
            //incoming format for PortPinger hostname[0] -p[1] portnumber[2] count[3]
            //getting ip address
            try
            {
                //tries to resolve the host frist
                var         host      = Convert.ToString(args[0]);
                IPAddress[] hostCheck = Dns.GetHostAddresses(host);
                var         port      = int.Parse(args[2]);

                Console.WriteLine("Ping Status To: {0} Port: {1}", host, port);
                Console.WriteLine("---------------------------");
                //default ping
                if (args.Length == 3)
                {
                    for (int i = 0; i != 4; i++)
                    {
                        try
                        {
                            //resolves the host name
                            IPAddress[] ip       = Dns.GetHostAddresses(host);
                            Socket      portPing = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                            IAsyncResult waiting = portPing.BeginConnect(host, port, null, null);
                            bool         success = waiting.AsyncWaitHandle.WaitOne(1200, true);

                            if (portPing.Connected == true)
                            {
                                Console.WriteLine("Address: {0} Port: {1} TTL: {2} Status: OPEN", host, port, portPing.Ttl);
                                portPing.Close();
                                Thread.Sleep(500);
                            }
                            else if (portPing.Connected == false)
                            {
                                Console.WriteLine("Address: {0} Port: {1} TTL: {2} Status: CLOSED", host, port, portPing.Ttl);
                                portPing.Close();
                            }
                        }
                        catch (SocketException e)
                        {
                            if (e.SocketErrorCode == SocketError.ConnectionRefused)
                            {
                                Socket portPing = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                                Console.WriteLine("Address: {0} Port: {1} TTL: {2} Status: FILTERED", host, port, portPing.Ttl);
                            }
                            else
                            {
                                Socket portPing = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                                Console.WriteLine("Address: {0} Port: {1} TTL: {2} Status: CLOSED", host, port, portPing.Ttl);
                            }
                        }
                    }
                }

                //continous ping
                else if (Convert.ToInt64(args[3]) == 0)
                {
                    while (true)
                    {
                        try
                        {
                            //resolves the host name
                            IPAddress[]  ip       = Dns.GetHostAddresses(host);
                            Socket       portPing = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                            IAsyncResult waiting  = portPing.BeginConnect(host, port, null, null);
                            bool         success  = waiting.AsyncWaitHandle.WaitOne(1000, true);
                            if (portPing.Connected == true)
                            {
                                Console.WriteLine("Address: {0} Port: {1} TTL: {2} Status: OPEN", host, port, portPing.Ttl);
                                portPing.Close();
                                Thread.Sleep(500);
                            }
                            else if (portPing.Connected == false)
                            {
                                Console.WriteLine("Address: {0} Port: {1} TTL: {2} Status: CLOSED", host, port, portPing.Ttl);
                                portPing.Close();
                            }
                        }
                        catch (SocketException e)
                        {
                            if (e.SocketErrorCode == SocketError.ConnectionRefused)
                            {
                                Socket portPing = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                                Console.WriteLine("Address: {0} Port: {1} TTL: {2} Status: FILTERED", host, port, portPing.Ttl);
                            }
                            else
                            {
                                Socket portPing = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                                Console.WriteLine("Address: {0} Port: {1} TTL: {2} Status: CLOSED", host, port, portPing.Ttl);
                            }
                        }
                    }
                }

                //user customer reply count
                else
                {
                    var count = Convert.ToInt64(args[3]);
                    for (int i = 0; i != count; i++)
                    {
                        try
                        {
                            //resolves the host name
                            IPAddress[] ip       = Dns.GetHostAddresses(host);
                            Socket      portPing = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                            IAsyncResult waiting = portPing.BeginConnect(host, port, null, null);
                            bool         success = waiting.AsyncWaitHandle.WaitOne(1000, true);
                            if (portPing.Connected == true)
                            {
                                Console.WriteLine("Address: {0} Port: {1} TTL: {2} Status: OPEN", host, port, portPing.Ttl);
                                portPing.Close();
                                Thread.Sleep(500);
                            }
                            else if (portPing.Connected == false)
                            {
                                Console.WriteLine("Address: {0} Port: {1} TTL: {2} Status: CLOSED", host, port, portPing.Ttl);
                                portPing.Close();
                            }
                        }
                        catch (SocketException e)
                        {
                            if (e.SocketErrorCode == SocketError.ConnectionRefused)
                            {
                                Socket portPing = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                                Console.WriteLine("Address: {0} Port: {1} TTL: {2} Status: FILTERED", host, port, portPing.Ttl);
                            }
                            else
                            {
                                Socket portPing = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                                Console.WriteLine("Address: {0} Port: {1} TTL: {2} Status: CLOSED", host, port, portPing.Ttl);
                            }
                        }
                    }
                }
            }

            //Socket error when the host cannot be resolved
            catch (SocketException)
            {
                var host = Convert.ToString(args[0]);
                Console.WriteLine("Address: {0}", host);
                Console.WriteLine("---------------------------");
                Console.WriteLine("Cannot resolve host name");
            }
        }
        public static bool StartClient(string str_empaticaDevice = "AB2B64")
        {
            // Connect to a remote device.
            try
            {
                m_startsaving = false;

                // Establish the remote endpoint for the socket.
                var ipHostInfo = new IPHostEntry {
                    AddressList = new[] { IPAddress.Parse(ServerAddress) }
                };
                var ipAddress = ipHostInfo.AddressList[0];
                var remoteEp  = new IPEndPoint(ipAddress, ServerPort);

                // Create a TCP/IP socket.
                //var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                // Connect to the remote endpoint.
                try
                {
                    client.BeginConnect(remoteEp, (ConnectCallback), client);
                    ConnectDone.WaitOne();
                }
                catch
                {
                    Console.WriteLine("start client");
                }


                /*
                 * device_connect 9ff167
                 * R device_connect OK
                 *
                 * device_subscribe bvp ON
                 * R device_subscribe bvp OK
                 *
                 * E4_Bvp 123345627891.123 31.128
                 *
                 * device_disconnect
                 * device_disconnect OK
                 *
                 *  acc - 3-axis acceleration
                 *  bvp - Blood Volume Pulse
                 *  gsr - Galvanic Skin Response
                 *  ibi - Interbeat Interval and Heartbeat
                 *  tmp - Skin Temperature
                 *  bat - Device Battery
                 *  tag - Tag taken from the device (by pressing the button)
                 *
                 */
                string[] list_empatica_device_management_msg = { "device_list", "device_connect " + str_empaticaDevice }; //AB2B64,9ff167, "device_disconnect"



                /*
                 * string [] list_empatica_datatype_msg ={
                 *  "device_subscribe acc ON",
                 *  "device_subscribe bvp ON",
                 *  "device_subscribe gsr ON",
                 *  "device_subscribe ibi ON",
                 *  "device_subscribe tmp ON",
                 *  "device_subscribe bat ON",
                 *  "device_subscribe tag ON" };
                 */
                System.Threading.Thread.Sleep(1000);//2000
                foreach (string item in list_empatica_device_management_msg)
                {
                    Send(client, item + Environment.NewLine);
                    SendDone.WaitOne();
                    Receive(client);
                    ReceiveDone.WaitOne();
                    System.Threading.Thread.Sleep(500);//2000
                }
                foreach (string item in list_empatica_datatype_msg)
                {
                    Send(client, item + Environment.NewLine);
                    SendDone.WaitOne();
                    Receive(client);
                    ReceiveDone.WaitOne();
                    System.Threading.Thread.Sleep(100);//2000
                }

                /*
                 * while (true)
                 * {
                 *  var msg = Console.ReadLine();
                 *  Send(client, msg + Environment.NewLine);
                 *  SendDone.WaitOne();
                 *  Receive(client);
                 *  ReceiveDone.WaitOne();
                 * }
                 */
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                return(false);
            }
            return(true);
        }
예제 #50
0
        /// <summary>
        /// Prints the label.
        /// </summary>
        /// <param name="person">The person.</param>
        private void PrintLabel(int personId, int locationId, int scheduleId)
        {
            CheckInPerson selectedPerson = CurrentCheckInState.CheckIn.Families.Where(f => f.Selected).FirstOrDefault()
                                           .People.Where(p => p.Person.Id == personId).FirstOrDefault();
            List <CheckInGroupType> selectedGroupTypes = selectedPerson.GroupTypes.Where(gt => gt.Selected &&
                                                                                         gt.Groups.Any(g => g.Selected && g.Locations.Any(l => l.Location.Id == locationId &&
                                                                                                                                          l.Schedules.Any(s => s.Schedule.Id == scheduleId)))).ToList();

            foreach (var groupType in selectedGroupTypes)
            {
                var printFromClient = groupType.Labels.Where(l => l.PrintFrom == Rock.Model.PrintFrom.Client);
                if (printFromClient.Any())
                {
                    AddLabelScript(printFromClient.ToJson());
                }

                var printFromServer = groupType.Labels.Where(l => l.PrintFrom == Rock.Model.PrintFrom.Server);
                if (printFromServer.Any())
                {
                    Socket socket    = null;
                    string currentIp = string.Empty;

                    foreach (var label in printFromServer)
                    {
                        var labelCache = KioskLabel.Read(label.FileId);
                        if (labelCache != null)
                        {
                            if (label.PrinterAddress != currentIp)
                            {
                                if (socket != null && socket.Connected)
                                {
                                    socket.Shutdown(SocketShutdown.Both);
                                    socket.Close();
                                }

                                currentIp = label.PrinterAddress;
                                var printerIp = new IPEndPoint(IPAddress.Parse(currentIp), 9100);

                                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                                IAsyncResult result  = socket.BeginConnect(printerIp, null, null);
                                bool         success = result.AsyncWaitHandle.WaitOne(5000, true);
                            }

                            string printContent = labelCache.FileContent;
                            foreach (var mergeField in label.MergeFields)
                            {
                                var rgx = new Regex(string.Format(@"(?<=\^FD){0}(?=\^FS)", mergeField.Key));
                                printContent = rgx.Replace(printContent, mergeField.Value);
                            }

                            if (socket.Connected)
                            {
                                var    ns     = new NetworkStream(socket);
                                byte[] toSend = System.Text.Encoding.ASCII.GetBytes(printContent);
                                ns.Write(toSend, 0, toSend.Length);
                            }
                            else
                            {
                                maWarning.Show("Could not connect to printer.", ModalAlertType.Warning);
                            }
                        }
                    }

                    if (socket != null && socket.Connected)
                    {
                        socket.Shutdown(SocketShutdown.Both);
                        socket.Close();
                    }
                }
            }
        }
예제 #51
0
    public static void TestConnect()
    {
        IAsyncResult ar1, ar2;
        TcpClient    cli;
        IPAddress    unaccessableHost = IPAddress.Parse("192.0.99.99");

        //--------------------------------------------------------------
        // Access before Connect.
        cli = new TcpClient();
        Assert.IsFalse(cli.Connected, "Connected");
        Assert.AreEqual(0, cli.Available, "Available");
        try {
            Stream s = cli.GetStream();
            Assert.Fail("SHaT!");
        } catch (Exception ex) {
            Assert.IsInstanceOfType(typeof(InvalidOperationException), ex, "InvalidOperationException and not a sub-type");
        }
        //--------------------------------------------------------------
        // BeginConnect twice -- first INCOMPLETE.
        cli = new TcpClient();
        ar1 = cli.BeginConnect(unaccessableHost, 80, null, null);
        try {
            ar2 = cli.BeginConnect(unaccessableHost, 80, null, null);
            Assert.Fail("SHaT!");
        } catch (Exception ex) {
            // BeginConnect twice: System.InvalidOperationException: BeginConnect cannot be called while another asynchronous operation is in progress on the same Socket.
            //Console.WriteLine("BeginConnect twice: " + FirstLine(ex));
            Assert.IsInstanceOfType(typeof(InvalidOperationException), ex, "InvalidOperationException and not a sub-type");
        }
        // cancel (the timing-out) connect
        try {
            cli.Close();
            cli.EndConnect(ar1);
            Assert.Fail("SHaT!");
        } catch (Exception) {
        }
        //--------------------------------------------------------------
        // BeginConnect twice -- first complete.
        cli = new TcpClient();
        ar1 = cli.BeginConnect("www.microsoft.com", 80, null, null);
        cli.EndConnect(ar1);
        ar2 = cli.BeginConnect("www.microsoft.com", 80, null, null);
        try {
            cli.EndConnect(ar2);
            Assert.Fail("SHaT!");
        } catch (Exception ex) {
            // BeginConnect twice after Begin/End: System.Net.Sockets.SocketException: A connect request was made on an already connected socket
            //Console.WriteLine("BeginConnect twice after Begin/End: " + FirstLine(ex));
            Assert.IsInstanceOfType(typeof(SocketException), ex);
            SocketException sex = (SocketException)ex;
            Assert.AreEqual((int)SocketError.IsConnected, sex.ErrorCode, "ErrorCode");
        }
        //--------------------------------------------------------------
        // Cancel an INCOMPLETE BeginConnect.
        cli = new TcpClient();
        ar1 = cli.BeginConnect(unaccessableHost, 80, null, null);
        Socket hackClient = cli.Client;

        // cancel (the timing-out) connect
        cli.Close();
        try {
            if (cli.Client == null)
            {
                // Eeeeeee: Dispose clears the Socket that EndConnect would use!!!
                hackClient.EndConnect(ar1);
            }
            else
            {
                cli.EndConnect(ar1);
                Assert.Fail("SHaT!");
            }
        } catch (ObjectDisposedException) {
        }
        // Socket--Cancel an INCOMPLETE BeginConnect.
        Socket sock = newClientSocket();

        ar1 = sock.BeginConnect(unaccessableHost, 80, null, null);
        // cancel (the timing-out) connect
        sock.Close();
        try {
            sock.EndConnect(ar1);
        } catch (ObjectDisposedException) {
        }
        //--------------------------------------------------------------
    }
예제 #52
0
        public static bool DoConnect(Socket fd, EndPoint addr, EndPoint?sourceAddr)
        {
            EndPoint?bindAddr = sourceAddr;

            if (bindAddr == null)
            {
                //
                // Even though we are on the client side, the call to Bind()
                // is necessary to work around a .NET bug: if a socket is
                // connected non-blocking, the LocalEndPoint and RemoteEndPoint
                // properties are null. The call to Bind() fixes this.
                //
                IPAddress any = fd.AddressFamily == AddressFamily.InterNetworkV6 ? IPAddress.IPv6Any : IPAddress.Any;
                bindAddr = new IPEndPoint(any, 0);
            }
            DoBind(fd, bindAddr);

repeatConnect:
            try
            {
                IAsyncResult result = fd.BeginConnect(addr, null, null);
                if (!result.CompletedSynchronously)
                {
                    return(false);
                }
                fd.EndConnect(result);
            }
            catch (SocketException ex)
            {
                if (Interrupted(ex))
                {
                    goto repeatConnect;
                }

                CloseSocketNoThrow(fd);

                if (ConnectionRefused(ex))
                {
                    throw new Ice.ConnectionRefusedException(ex);
                }
                else
                {
                    throw new Ice.ConnectFailedException(ex);
                }
            }

            //
            // On Windows, we need to set the socket's blocking status again
            // after the asynchronous connect. Seems like a bug in .NET.
            //
            SetBlock(fd, fd.Blocking);
            if (!Ice.AssemblyUtil.IsWindows)
            {
                //
                // Prevent self connect (self connect happens on Linux when a client tries to connect to
                // a server which was just deactivated if the client socket re-uses the same ephemeral
                // port as the server).
                //
                if (addr.Equals(GetLocalAddress(fd)))
                {
                    throw new Ice.ConnectionRefusedException();
                }
            }
            return(true);
        }
 public void Connect(string hostName, int port, ConnectCallBack callBack)
 {
     _connectCallBack = callBack;
     _baseSocket.BeginConnect(hostName, port, connectCallBack, null);
 }
예제 #54
0
        //IP_AD is the IP address of the server
        private void connect(string IP_AD)
        {
            try
            {
                //init
                IPAddress  ipAddress = IPAddress.Parse(IP_AD);
                IPEndPoint remoteEP  = new IPEndPoint(ipAddress, port);
                Socket     client    = new Socket(AddressFamily.InterNetwork,
                                                  SocketType.Stream, ProtocolType.Tcp);

                //Connect through the remote socket (endpoint)
                client.BeginConnect(remoteEP,
                                    new AsyncCallback(ConnectCallback), client);
                connectDone.WaitOne();
                // Send test data to the remote device.
                SendBytes(client, getLoginProtocol());
                sendDone.WaitOne();

                // Receive the response from the remote device.
                Receive(client);
                receiveDone.WaitOne();

                // Write the response to the console.
                //Response: First byte (0) is verification that the packet is a type 1 packet
                //Second byte is pass (0) or fail(1) for authorization
                //Next (3) bytes are authoization bytes (512 bit authorization)
                if (receivedpacket[0] == 1)
                {
                    if (receivedpacket[1] == 0)
                    {
                        //Wrong name or password entered by user
                        label2.Text = "Name or Password Incorrect.";
                        textAlign();
                        verificationcode[0] = Convert.ToByte(0);
                        verificationcode[1] = Convert.ToByte(0);
                        verificationcode[2] = Convert.ToByte(0);
                    }
                    else
                    {
                        //Verified that login is good
                        verificationcode[0] = receivedpacket[2];
                        verificationcode[1] = receivedpacket[3];
                        verificationcode[2] = receivedpacket[4];
                        Console.WriteLine("Login Packet Authorization complete");
                        //textAlign();

                        bool su = false;
                        if (receivedpacket[5] == 1)
                        {
                            su = true;
                        }

                        //Transfer to main form
                        verify(su);
                        this.Hide();

                        mainForm.Show();
                    }
                }
                else
                {
                    Console.WriteLine("A fatal error has occurred: Incorrect packet type returned by server to login verification protocol");
                }
                Console.WriteLine("Verification code: " + Convert.ToInt32(verificationcode[0]) + Convert.ToInt32(verificationcode[1]) + Convert.ToInt32(verificationcode[2]));

                // Release the socket.
                //client.Shutdown(SocketShutdown.Both);
                //client.Close();
                //client.Dispose();
                //client = null;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
예제 #55
0
        /// <summary>
        /// Connect to the specified host
        /// </summary>
        /// <param name="host">The host to connect to</param>
        /// <param name="port">The port to connect to</param>
        /// <param name="ipVersions">Internet Protocol versions to support during the connection phase</param>
        public async Task ConnectAsync(string host, int port, FtpIpVersion ipVersions)
        {
            IPAddress[] addresses = await Dns.GetHostAddressesAsync(host);

            if (ipVersions == 0)
            {
                throw new ArgumentException("The ipVersions parameter must contain at least 1 flag.");
            }

            for (int i = 0; i < addresses.Length; i++)
            {
                // we don't need to do this check unless
                // a particular version of IP has been
                // omitted so we won't.
                if (ipVersions != FtpIpVersion.ANY)
                {
                    switch (addresses[i].AddressFamily)
                    {
                    case AddressFamily.InterNetwork:
                        if ((ipVersions & FtpIpVersion.IPv4) != FtpIpVersion.IPv4)
                        {
#if DEBUG
                            FtpTrace.WriteStatus(FtpTraceLevel.Verbose, "Skipped IPV4 address : " + addresses[i].ToString());
#endif
                            continue;
                        }
                        break;

                    case AddressFamily.InterNetworkV6:
                        if ((ipVersions & FtpIpVersion.IPv6) != FtpIpVersion.IPv6)
                        {
#if DEBUG
                            FtpTrace.WriteStatus(FtpTraceLevel.Verbose, "Skipped IPV6 address : " + addresses[i].ToString());
#endif
                            continue;
                        }
                        break;
                    }
                }

                if (FtpTrace.LogIP)
                {
                    FtpTrace.WriteStatus(FtpTraceLevel.Info, "Connecting to " + addresses[i].ToString() + ":" + port);
                }
                else
                {
                    FtpTrace.WriteStatus(FtpTraceLevel.Info, "Connecting to ***:" + port);
                }

                m_socket = new Socket(addresses[i].AddressFamily, SocketType.Stream, ProtocolType.Tcp);

#if CORE
                await m_socket.ConnectAsync(addresses[i], port);

                break;
#else
                var connectResult = m_socket.BeginConnect(addresses[i], port, null, null);
                await Task.Factory.FromAsync(connectResult, m_socket.EndConnect);

                break;
#endif
            }

            // make sure that we actually connected to
            // one of the addresses returned from GetHostAddresses()
            if (m_socket == null || !m_socket.Connected)
            {
                Close();
                throw new IOException("Failed to connect to host.");
            }

            m_netStream             = new NetworkStream(m_socket);
            m_netStream.ReadTimeout = m_readTimeout;
            m_lastActivity          = DateTime.Now;
        }
예제 #56
0
        static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.DarkGray;
            var aStopwatch = new Stopwatch();
            var hostArg    = args.FirstOrDefault() ?? "8.8.8.8";
            var host       = hostArg.Contains("://")
                ? new Uri(hostArg)
                : new Uri("http://" + hostArg);
            var point = host.HostNameType == UriHostNameType.Dns
                ? new IPEndPoint(Dns.GetHostAddresses(host.Host).FirstOrDefault(), host.Port)
                : new IPEndPoint(IPAddress.Parse(host.Host), host.Port);
            var tasks = new List <Task>();
            var ports = new List <int>();

            aStopwatch.Start();
            Parallel.For(1, 65535, i =>
            {
                var bgWorker     = new BackgroundWorker();
                bgWorker.DoWork += (sender, eventArgs) =>
                {
                    var i1 = i;
                    var t  = Task.Run(() =>
                    {
                        var conn      = true;
                        var stopWatch = new Stopwatch();
                        stopWatch.Start();
                        try
                        {
                            var socks = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
                            {
                                Blocking       = false,
                                ReceiveTimeout = 100,
                                SendTimeout    = 100
                            };
                            var result = socks.BeginConnect(new IPEndPoint(point.Address, i1), null, null);
                            if (!result.AsyncWaitHandle.WaitOne(100, true))
                            {
                                conn = false;
                            }
                            else
                            {
                                socks.Close(100);
                            }
                        }
                        catch (Exception exception)
                        {
                            Console.WriteLine(exception.Message);
                            conn = false;
                        }

                        stopWatch.Stop();
                        var time = Convert.ToInt32(stopWatch.Elapsed.TotalMilliseconds);
                        if (conn)
                        {
                            ports.Add(i1);
                            Console.ForegroundColor = ConsoleColor.Green;
                        }
                        Console.WriteLine($"来自 {point.Address}:{i1} 的 TCP 响应: 端口={conn} 时间={time}ms");
                        Console.ForegroundColor = ConsoleColor.DarkGray;
                    });
                    tasks.Add(t);
                };
                bgWorker.RunWorkerAsync();
            });

            //while (!parallel.IsCompleted){}

            Task.WaitAll(tasks.ToArray());
            aStopwatch.Stop();
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Done!");
            Console.WriteLine(string.Join(" ", ports));
            Console.WriteLine(Convert.ToInt32(aStopwatch.Elapsed.TotalSeconds));
        }
예제 #57
0
        /// <summary>
        /// Connect to the specified host
        /// </summary>
        /// <param name="host">The host to connect to</param>
        /// <param name="port">The port to connect to</param>
        /// <param name="ipVersions">Internet Protocol versions to support during the connection phase</param>
        public void Connect(string host, int port, FtpIpVersion ipVersions)
        {
#if CORE
            IPAddress[] addresses = Dns.GetHostAddressesAsync(host).Result;
#else
            IAsyncResult ar        = null;
            IPAddress[]  addresses = Dns.GetHostAddresses(host);
#endif

            if (ipVersions == 0)
            {
                throw new ArgumentException("The ipVersions parameter must contain at least 1 flag.");
            }

            for (int i = 0; i < addresses.Length; i++)
            {
                // we don't need to do this check unless
                // a particular version of IP has been
                // omitted so we won't.
                if (ipVersions != FtpIpVersion.ANY)
                {
                    switch (addresses[i].AddressFamily)
                    {
                    case AddressFamily.InterNetwork:
                        if ((ipVersions & FtpIpVersion.IPv4) != FtpIpVersion.IPv4)
                        {
#if DEBUG
                            FtpTrace.WriteStatus(FtpTraceLevel.Verbose, "Skipped IPV4 address : " + addresses[i].ToString());
#endif
                            continue;
                        }
                        break;

                    case AddressFamily.InterNetworkV6:
                        if ((ipVersions & FtpIpVersion.IPv6) != FtpIpVersion.IPv6)
                        {
#if DEBUG
                            FtpTrace.WriteStatus(FtpTraceLevel.Verbose, "Skipped IPV6 address : " + addresses[i].ToString());
#endif
                            continue;
                        }
                        break;
                    }
                }

                if (FtpTrace.LogIP)
                {
                    FtpTrace.WriteStatus(FtpTraceLevel.Info, "Connecting to " + addresses[i].ToString() + ":" + port);
                }
                else
                {
                    FtpTrace.WriteStatus(FtpTraceLevel.Info, "Connecting to ***:" + port);
                }

                m_socket = new Socket(addresses[i].AddressFamily, SocketType.Stream, ProtocolType.Tcp);
#if CORE
                m_socket.ConnectAsync(addresses[i], port).Wait();
                break;
#else
                ar = m_socket.BeginConnect(addresses[i], port, null, null);
                if (!ar.AsyncWaitHandle.WaitOne(m_connectTimeout, true))
                {
                    Close();

                    // check to see if we're out of addresses, and throw a TimeoutException
                    if ((i + 1) == addresses.Length)
                    {
                        throw new TimeoutException("Timed out trying to connect!");
                    }
                }
                else
                {
                    m_socket.EndConnect(ar);
                    // we got a connection, break out
                    // of the loop.
                    break;
                }
#endif
            }

            // make sure that we actually connected to
            // one of the addresses returned from GetHostAddresses()
            if (m_socket == null || !m_socket.Connected)
            {
                Close();
                throw new IOException("Failed to connect to host.");
            }

            m_netStream             = new NetworkStream(m_socket);
            m_netStream.ReadTimeout = m_readTimeout;
            m_lastActivity          = DateTime.Now;
        }
예제 #58
0
 private static Task ConnectAsync(Socket socket, IPEndPoint endPoint)
 {
     return(Task.Factory.FromAsync((cb, state) => socket.BeginConnect(endPoint, cb, state), ar => socket.EndConnect(ar), null));
 }
예제 #59
0
        public static Socket Connect(IPEndPoint remoteEndpoint, TimeSpan connectTimeout)
        {
            var socket = new Socket(remoteEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)
            {
                NoDelay = true
            };

#if FEATURE_SOCKET_EAP
            var connectCompleted = new ManualResetEvent(false);
            var args             = new SocketAsyncEventArgs
            {
                UserToken      = connectCompleted,
                RemoteEndPoint = remoteEndpoint
            };
            args.Completed += ConnectCompleted;

            if (socket.ConnectAsync(args))
            {
                if (!connectCompleted.WaitOne(connectTimeout))
                {
                    // avoid ObjectDisposedException in ConnectCompleted
                    args.Completed -= ConnectCompleted;
                    // avoid leaking threads and /Device/Afd handles

                    //TODO: uncomment this when Mono code is available Socket.CancelConnectAsync(args);
                    // dispose Socket
                    socket.Dispose();
                    // dispose ManualResetEvent
                    connectCompleted.Dispose();
                    // dispose SocketAsyncEventArgs
                    args.Dispose();

                    throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture,
                                                                         "Connection failed to establish within {0:F0} milliseconds.",
                                                                         connectTimeout.TotalMilliseconds));
                }
            }

            // dispose ManualResetEvent
            connectCompleted.Dispose();

            if (args.SocketError != SocketError.Success)
            {
                var socketError = (int)args.SocketError;

                // dispose Socket
                socket.Dispose();
                // dispose SocketAsyncEventArgs
                args.Dispose();

                throw new SocketException(socketError);
            }

            // dispose SocketAsyncEventArgs
            args.Dispose();

            return(socket);
#elif FEATURE_SOCKET_APM
            var connectResult = socket.BeginConnect(remoteEndpoint, null, null);
            if (!connectResult.AsyncWaitHandle.WaitOne(connectTimeout, false))
            {
                throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture,
                                                                     "Connection failed to establish within {0:F0} milliseconds.", connectTimeout.TotalMilliseconds));
            }
            socket.EndConnect(connectResult);
            return(socket);
#elif FEATURE_SOCKET_TAP
            if (!socket.ConnectAsync(remoteEndpoint).Wait(connectTimeout))
            {
                throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture,
                                                                     "Connection failed to establish within {0:F0} milliseconds.", connectTimeout.TotalMilliseconds));
            }
            return(socket);
#else
            #error Connecting to a remote endpoint is not implemented.
#endif
        }
예제 #60
0
        /// <summary>
        /// initialize pomelo client
        /// </summary>
        /// <param name="host">server name or server ip (www.xxx.com/127.0.0.1/::1/localhost etc.)</param>
        /// <param name="port">server port</param>
        /// <param name="callback">socket successfully connected callback(in network thread)</param>
        public void initClient(string host, int port, Action callback = null)
        {
            timeoutEvent.Reset();
            eventManager = new EventManager();
            NetWorkChanged(NetWorkState.CONNECTING);

            IPAddress ipAddress = null;

            try
            {
                IPAddress[] addresses = Dns.GetHostEntry(host).AddressList;
                foreach (var item in addresses)
                {
                    if (item.AddressFamily == AddressFamily.InterNetwork)
                    {
                        ipAddress = item;
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                Debug.Log("------------>" + e.ToString());
                NetWorkChanged(NetWorkState.ERROR);
                return;
            }

            if (ipAddress == null)
            {
                throw new Exception("can not parse host : " + host);
            }

            this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ie = new IPEndPoint(ipAddress, port);

            socket.BeginConnect(ie, new AsyncCallback((result) =>
            {
                try
                {
                    this.socket.EndConnect(result);
                    this.protocol = new Protocol(this, this.socket);
                    NetWorkChanged(NetWorkState.CONNECTED);

                    if (callback != null)
                    {
                        callback();
                    }
                }
                catch (SocketException e)
                {
                    if (netWorkState != NetWorkState.TIMEOUT)
                    {
                        NetWorkChanged(NetWorkState.ERROR);
                    }
                    Dispose();
                }
                finally
                {
                    timeoutEvent.Set();
                }
            }), this.socket);

            if (timeoutEvent.WaitOne(timeoutMSec, false))
            {
                if (netWorkState != NetWorkState.CONNECTED && netWorkState != NetWorkState.ERROR)
                {
                    NetWorkChanged(NetWorkState.TIMEOUT);
                    Dispose();
                }
            }
        }