BeginConnect() public méthode

public BeginConnect ( EndPoint remoteEP, AsyncCallback callback, object state ) : IAsyncResult
remoteEP System.Net.EndPoint
callback AsyncCallback
state object
Résultat IAsyncResult
        private void button1_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            var ControllerIPAddress = new IPAddress(new byte[] { 192, 168, 0, 2 });
            var ControllerPort = 40001;
            var ControllerEndPoint = new IPEndPoint(ControllerIPAddress, ControllerPort);
            _client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            var header = "@";
            var command = "00C";
            var checksum = "E3";
            var end = "\r\n";
            var data = header + command + checksum + end;
            byte[] bytes = new byte[1024];

            //Start Connect
            _connectDone.Reset();
            watch.Start();
            _client.BeginConnect(ControllerIPAddress, ControllerPort, new AsyncCallback(ConnectCallback), _client);
            //wait 2s
            _connectDone.WaitOne(2000, false);

            var text = (_client.Connected) ? "ok" : "ng";
            richTextBox1.AppendText(text + "\r\n");
            watch.Stop();
            richTextBox1.AppendText("Consumer time: " + watch.ElapsedMilliseconds + "\r\n");
        }
        private Boolean BindConnection(IPAddress TerminalAddress, Int16 TerminalPort)
        {
            System.Net.IPEndPoint _remoteEndPoint = new System.Net.IPEndPoint(TerminalAddress, TerminalPort);
            IAsyncResult          result          = TerminalSocket.BeginConnect(TerminalAddress, TerminalPort, null, null);

            return(result.AsyncWaitHandle.WaitOne(new TimeSpan(0, 0, 10), true));
        }
Exemple #3
0
        private static bool IsPortOpen(IPAddress ipAddress, int currentPort, int connectTimeout)
        {
            bool portIsOpen = false;

            //use raw Sockets
            //using TclClient along with IAsyncResult can lead to ObjectDisposedException on Linux+Mono
            Socket socket = null;
            try
            {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, false);

                IAsyncResult result = socket.BeginConnect(ipAddress.ToString(), currentPort, null, null);
                result.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(connectTimeout), true);

                portIsOpen = socket.Connected;
            }
            catch
            {
            }
            finally
            {
                if (socket != null)
                    socket.Close();
            }

            return portIsOpen;
        }
Exemple #4
0
 /// <summary>
 /// 异步连接服务器
 /// </summary>
 public void Connect(IPEndPoint ipEndPoint)
 {
     if (_connectState != NetworkClientState.Closed)
     {
         if (onConnected != null)
         {
             onConnected.Invoke();
         }
         Debug.Log("客户端非关闭状态,无法进行该操作!");
         return;
     }
     _currentIpEndPoint = ipEndPoint;
     _connectState      = NetworkClientState.Connecting;
     _unityInvoke       = new UnityInvoke("SocketClient");
     Debug.Log("connect Start");
     try
     {
         _msgCounter = 0;
         _socket     = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
         _socket.BeginConnect(ipEndPoint, DoConnect, _socket);
     }
     catch (Exception ex)
     {
         Debug.Log(ex.ToString());
     }
 }
        public PooledSocket(IPEndPoint endpoint, TimeSpan connectionTimeout, TimeSpan receiveTimeout)
        {
            var socket = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            // all operations are "atomic", we do not send small chunks of data
            socket.NoDelay = true;

            var mre = new ManualResetEvent(false);
            var timeout = connectionTimeout == TimeSpan.MaxValue
                            ? Timeout.Infinite
                            : (int)connectionTimeout.TotalMilliseconds;

            socket.ReceiveTimeout = (int)receiveTimeout.TotalMilliseconds;
            socket.SendTimeout = (int)receiveTimeout.TotalMilliseconds;

            socket.BeginConnect(endpoint, iar =>
            {
                try { using (iar.AsyncWaitHandle) socket.EndConnect(iar); }
                catch { }

                mre.Set();
            }, null);

            if (!mre.WaitOne(timeout) || !socket.Connected)
            {
                using (socket)
                    throw new TimeoutException("Could not connect to " + endpoint);
            }

            this.socket = socket;
            this.endpoint = endpoint;

            this.inputStream = new BufferedStream(new BasicNetworkStream(socket));
        }
 Task<ActiveConnectResult> IActiveConnector.ActiveConnect(EndPoint targetEndPoint)
 {
     var taskSource = new TaskCompletionSource<ActiveConnectResult>();
     var socket = new Socket(targetEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
     socket.BeginConnect(targetEndPoint, OnActiveConnectCallback, new ActiveConnectState(taskSource, socket));
     return taskSource.Task;
 }
Exemple #7
0
        //public Socket communicateSocket = null;
        //客户端重载Access函数
        public override void Access(string IP, string Port, string PortSelf, System.Action AccessAction)
        {
            communicateSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            communicateSocket.Bind(new IPEndPoint(IPAddress.Any, int.Parse(PortSelf)));

            //服务器的IP和端口
            IPEndPoint serverIP;
            try
            {
                serverIP = new IPEndPoint(IPAddress.Parse(IP), int.Parse(Port));
            }
            catch
            {
                throw new Exception(String.Format("{0} is not a valid IP Address!", IP));
            }

            //客户端只用来向指定的服务器发送信息,不需要绑定本机的IP和端口,不需要监听
            try
            {
                communicateSocket.BeginConnect(serverIP, ar =>
                {
                    AccessAction();
                }, null);
            }
            catch
            {
                throw new Exception(string.Format("Fail to connect {0}!", IP));
            }
        }
Exemple #8
0
        /// <summary>
        /// Starts the auth-server connection
        /// </summary>
        /// <returns>true on success, false otherwise</returns>
        public bool Start()
        {
            Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp);

            try
            {
                // Parse string IP Address
                IPAddress ip;
                if (!IPAddress.TryParse(Settings.AuthServerIP, out ip))
                {
                    ConsoleUtils.ShowFatalError("Failed to parse Server IP ({0})", Settings.ServerIP);
                    return false;
                }
                // Connect
                socket.BeginConnect(new IPEndPoint(ip, Settings.AuthServerPort), new AsyncCallback(ConnectCallback), socket);
            }
            catch (Exception e)
            {
                ConsoleUtils.ShowError(e.Message);
                ConsoleUtils.ShowError("At AuthManager.Start()");

                socket.Close();
                return false;
            }

            return true;
        }
            public void Start(byte[] firstPacket, int length, Socket socket, int targetPort)
            {
                this._firstPacket = firstPacket;
                this._firstPacketLength = length;
                this._local = socket;
                try
                {
                    // TODO async resolving
                    IPAddress ipAddress;
                    bool parsed = IPAddress.TryParse("127.0.0.1", out ipAddress);
                    IPEndPoint remoteEP = new IPEndPoint(ipAddress, targetPort);


                    _remote = new Socket(ipAddress.AddressFamily,
                        SocketType.Stream, ProtocolType.Tcp);
                    _remote.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);

                    // Connect to the remote endpoint.
                    _remote.BeginConnect(remoteEP,
                        new AsyncCallback(ConnectCallback), null);
                }
                catch (Exception e)
                {
                    Logging.LogUsefulException(e);
                    this.Close();
                }
            }
        public static ScanMessage Connect(EndPoint remoteEndPoint, int timeout)
        {
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            TcpConnectCall connectCall = new TcpConnectCall(socket);

            // Need for controlling timeout period introduces us to asynccallback methods
            AsyncCallback connectedCallback = new AsyncCallback(connectCall.ConnectedCallback);

            try
            {
                IAsyncResult result = socket.BeginConnect(remoteEndPoint, connectedCallback, socket);

                // wait for timeout to connect
                if (result.AsyncWaitHandle.WaitOne(timeout, false) == false)
                {
                    return ScanMessage.Timeout;
                }
                else
                {
                    Exception connectException = connectCall.connectFailureException;
                    if (connectException != null)
                    {
                        return ScanMessage.PortClosed;
                    }

                    return ScanMessage.PortOpened;
                }
            }
            finally
            {
                socket.Close();
            }
        }
Exemple #11
0
 internal static void Join(IPAddress ip, int nPort)
 {
     Connection_attempt = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
     IPEndPoint ipRemote = new IPEndPoint(ip, nPort);
     Connection_attempt.BeginConnect(ipRemote, new AsyncCallback(OnRemoteConnect), null);
     Connecting = true;
 }
Exemple #12
0
        private void Client_Form_Load(object sender, EventArgs e)
        {
            try
            {
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
                //Server is listening on port 1000
                IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 1000);

                //Connect to the server
                clientSocket.BeginConnect(ipEndPoint, new AsyncCallback(OnConnect), null);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SGSclient", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            byteData = new byte[1024];
            //Start listening to the data asynchronously
            clientSocket.BeginReceive(byteData,
                                       0,
                                       byteData.Length,
                                       SocketFlags.None,
                                       new AsyncCallback(OnReceive),
                                       null);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ProScanMobile.NetworkConnection"/> class.
        /// </summary>
        /// <description>
        /// Creates a new _tcpSocket and tries to connect to Host/Port 
        /// </description>
        /// <param name="host">Host</param>
        /// <param name="port">Port</param>
        public NetworkConnection(string host, int port)
        {
            _connectDone.Reset ();

            try
            {
                IPHostEntry ipHostInfo = Dns.GetHostEntry (host);
                IPAddress ipAddress = ipHostInfo.AddressList [0];
                IPEndPoint remoteEP = new IPEndPoint (ipAddress, port);

                _tcpSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                _tcpSocket.Blocking = true;

                var result = _tcpSocket.BeginConnect (remoteEP, null, null);

                bool success = result.AsyncWaitHandle.WaitOne (5000, true);
                if (success) {
                    _tcpSocket.EndConnect (result);
                    _connectionStatus = ConnectionStatus.Connected;
                    _connectionStatusMessage = "Connected.";
                } else {
                    _tcpSocket.Close ();
                    _connectionStatus = ConnectionStatus.Error;
                    _connectionStatusMessage = "Connection timed out.";
                }
            } catch {
                _connectionStatus = ConnectionStatus.Error;
                _connectionStatusMessage = string.Format("An error occured connecting to {0} on port {1}.", host, port);
                _connectDone.Set();
                return;
            } finally {
                _connectDone.Set ();
            }
        }
 public void init()
 {
     try
     {
         Console.WriteLine("Init");
         //set up socket
         Socket client = new Socket(AddressFamily.InterNetwork,
         SocketType.Stream, ProtocolType.Tcp);
         //IPHostEntry hostInfo = Dns.Resolve("localhost:8000");
         //IPAddress address = hostInfo.AddressList[0];
         //IPAddress ipAddress = Dns.GetHostEntry("localhost:8000").AddressList[0];
         IPAddress ipAddress = new IPAddress(new byte[] { 128, 61, 105, 215 });
         IPEndPoint ep = new IPEndPoint(ipAddress, 8085);
         client.BeginConnect(ep, new AsyncCallback(ConnectCallback), client);
         connectDone.WaitOne();
         //receiveForever(client);
         byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");
         StateObject state = new StateObject();
         state.workSocket = client;
         client.BeginReceive(buffer, 0, StateObject.BufferSize, 0,
                 new AsyncCallback(ReceiveCallback), state);
         client.Send(msg);
     }
     catch (Exception e)
     {
         Console.WriteLine(e.ToString());
     }
 }
        private System.Net.IPAddress getLocalConnectibleIP(string remoteIP, int remotePort)
        {
            string text = "127.0.0.1";

            System.Net.Sockets.Socket socket = null;
            try
            {
                socket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
                System.IAsyncResult asyncResult = socket.BeginConnect(remoteIP, remotePort, null, null);
                bool flag = asyncResult.AsyncWaitHandle.WaitOne(5000, true);
                if (flag && socket.Connected)
                {
                    text = this.GetLocalEndPoint(socket);
                    int length = text.IndexOf(":");
                    text = text.Substring(0, length);
                }
            }
            catch (System.Exception)
            {
            }
            finally
            {
                if (socket != null)
                {
                    socket.Close();
                }
            }
            return(System.Net.IPAddress.Parse(text));
        }
Exemple #16
0
        private void tp_TrackerUpdate(ArrayList peers, bool success, string errorMessage)
        {
            Config.LogDebugMessage("Tracker update: Success: " + success + " : Num Peers : " + (peers != null ? peers.Count.ToString() : "0"));

            // attempt to connect to each peer given
            if (success)
            {
                if (peers != null)
                {
                    foreach (PeerInformation peerinfo in peers)
                    {
                        Config.LogDebugMessage("Peer : " + peerinfo.IP + ":" + peerinfo.Port + " ID: " + (peerinfo.ID != null ? peerinfo.ID.ToString() : "NONE"));

                        try
                        {
                            Sockets.Socket socket = new Sockets.Socket(Sockets.AddressFamily.InterNetwork, Sockets.SocketType.Stream, Sockets.ProtocolType.Tcp);
                            socket.BeginConnect(new Net.IPEndPoint(Net.IPAddress.Parse(peerinfo.IP), peerinfo.Port),
                                                new System.AsyncCallback(StartPeerConnectionThread), new object[] { socket, peerinfo });
                        }
                        catch (System.Exception e)
                        {
                            Config.LogException(e);
                        }
                    }
                }
            }
            else
            {
                if (this.TrackerError != null)
                {
                    this.TrackerError(this, errorMessage);
                }
            }
        }
		/**
		 * Asynchronously connects to the localhost server on the cached port number.
		 * Sets up a TCP socket attempting to contact localhost:outPort, and a 
		 * corresponding UDP server, bound to the inPort.
		 * 
		 * UNDONE: Think about establishing TCP communication to request what port to set up,
		 * in case ports can't be directly forwarded, etc. and Unity doesn't know.
		 * 
		 * Returns True if the connection was successful, false otherwise.
		 */
		public bool connectAsync(){
			try { 
				/* Create TCP socket for authenticated communication */
				endpt = new IPEndPoint(IPAddress.Parse(host), outPort); 
				clientAuth = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

				clientAuth.BeginConnect(endpt, new AsyncCallback(connectCallback), clientAuth);

				/* Set up nondurable UDP server for receiving actions*/
				server = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
				server.Blocking = false;

				/*Set up nondurable UDP client to send gamestate */
				IPEndPoint RemoteEndPoint= new IPEndPoint(IPAddress.Parse(host), outPort);
				clientGameState = new Socket(AddressFamily.InterNetwork,SocketType.Dgram, ProtocolType.Udp);

				/* Bind to UDP host port */
				IPEndPoint inpt = new IPEndPoint(IPAddress.Parse(host), inPort);
				server.Bind (inpt);
				return true;

			} catch (Exception e){
				Debug.Log (e);
				return false;
			}
		}
        /**
         * Creates a new socket and connects to the specified host and port.
         *
         * @param strHost
         *   Host to connect to.
         * @param intPort
         *   Port to connect to.
         */
        public void BeginConnect(string strHost, int intPort, PenguinConnectCallback connectCallback)
        {
            penguinSocks = new Sockets.Socket(Sockets.AddressFamily.InterNetwork, Sockets.SocketType.Stream, Sockets.ProtocolType.Tcp);
            ConnectState connectionState = new ConnectState(strHost, intPort, connectCallback);

            penguinSocks.BeginConnect(System.Net.IPAddress.Parse(strHost), intPort, ConnectionCallback, connectionState);
        }
        public void Send(string message, bool isFile)
        {
            try
            {
                SerializationClass serCl = new SerializationClass();

                if (isFile)
                {
                    serCl.FileName = message.Substring(message.LastIndexOf('\\')+1);
                    serCl.Command = "SendFile";
                    using (FileStream file = new FileStream(message, FileMode.Open))
                    {
                        StreamReader sr = new StreamReader(file);
                        string cont = sr.ReadToEnd();
                        serCl.Content = Encoding.UTF8.GetBytes(cont);
                    }
                }
                else
                {
                    serCl.FileName = message;
                    serCl.Content = Encoding.UTF8.GetBytes(message);
                    serCl.Command = "SendMessage";
                }
                string msg = JsonConvert.SerializeObject(serCl);

                bytes = Encoding.UTF8.GetBytes(msg);
                sSender = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                AsyncCallback acConn = new AsyncCallback(OnConnect);
                sSender.BeginConnect(ipEnd, acConn, sSender);
            }
            catch (Exception exc)
            {

            }
        }
Exemple #20
0
        public void Connect(int port, string host  = null,
                            Action connectListener = null)
        {
            if (port < 1 || port > 65535)
            {
                throw new ArgumentOutOfRangeException("port");
            }

            host = host ?? "127.0.0.1";

            if (connectListener != null)
            {
                OnConnect += connectListener;
            }

            Core.EventLoop.Instance.Push(() =>
            {
                endPoint = new Wininet.IPEndPoint(
                    Wininet.IPAddress.Parse(host),
                    port);
            });

            Core.EventLoop.Instance.Push(() =>
            {
                nativeSocket.BeginConnect(endPoint,
                                          _static_endConnect, this);
            });
        }
		public telnetClient(string ip, int p, TextBox tb)
		{

			address = ip;
			port = p;
			textBox1=tb;
			IPHostEntry IPHost = Dns.Resolve(address); 
			string []aliases = IPHost.Aliases; 
			IPAddress[] addr = IPHost.AddressList; 
		
			try
			{
				// Create New Socket 
				s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
				// Create New EndPoint
				iep	= new IPEndPoint(addr[0],port);  
				// This is a non blocking IO
				s.Blocking		= false ;	
				// Assign Callback function to read from Asyncronous Socket
				callbackProc	= new AsyncCallback(ConnectCallback);
				// Begin Asyncronous Connection
				s.BeginConnect(iep , callbackProc, s ) ;				
		
			}
			catch(Exception eeeee )
			{
				MessageBox.Show(eeeee.Message , "Application Error!!!" , MessageBoxButtons.OK , MessageBoxIcon.Stop );
				Application.Exit();
			}
		}
Exemple #22
0
        private ActiveIO(Socket ssc, NetSession session, String hostName, int port)
        {
            (assoc_session = session).InitSession();
            //connectDone = new ManualResetEvent(false);
			//在 Unity 中 BeginConnect 解析域名阻塞,所以起线程
			new Thread(()=>ssc.BeginConnect(hostName, port, new AsyncCallback(ConnectCallback), ssc)).Start();
        }
Exemple #23
0
 protected virtual void OnBtnConnectClicked(object sender, System.EventArgs e)
 {
     try {
         clientSocket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork,
                                                      SocketType.Stream,
                                                      ProtocolType.Tcp);
         IPAddress ipAddress = IPAddress.Parse(txtIp.Text);
         log(txtIp.Text);
         IPEndPoint ipEndPoint = new IPEndPoint(ipAddress,
                                                int.Parse(txtPort.Text));
         clientSocket.BeginConnect(ipEndPoint,
                                   new AsyncCallback(OnConnect),
                                   null);
         btnConnect.Sensitive    = false;
         btnDisconnect.Sensitive = true;
         btnMsg.Sensitive        = true;
     }
     catch (Exception ex) {
         log("Not able to connect to server:");
         log(ex.Message);
         btnConnect.Sensitive    = true;
         btnDisconnect.Sensitive = false;
         btnMsg.Sensitive        = false;
     }
 }
Exemple #24
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(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);
                socket = client;
                running = true;
                // Connect to the remote endpoint.
                client.BeginConnect(remoteEP,
                    new AsyncCallback(ConnectCallback), client);
                connectDone.WaitOne();

                SendReceive(client, "Handshake<EOF>");


            }
            catch (Exception e)
            {
                ClientLog(null, new Logging.LogEventArgs(e.ToString()));
            }
        }
Exemple #25
0
        public bool Connect( string address, int remotePort )
        {
            if ( _socket != null && _socket.Connected )
            {
                return true;
            }

            //解析域名
            IPHostEntry hostEntry = Dns.GetHostEntry( address );

            foreach(IPAddress ip in hostEntry.AddressList)
            {
                try
                {
                    //获得远程服务器的地址
                    IPEndPoint ipe = new IPEndPoint( ip, remotePort );

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

                    //开始连接
                    _socket.BeginConnect( ipe, new System.AsyncCallback( ConnectionCallback ), _socket );

                    break;
                }
                catch(System.Exception e)
                {
                    //连接失败 将消息传入逻辑处理队列
                    PushPacket( (ushort)MessageIdentifiers.ID.CONNECTION_ATTEMPT_FAILED, e.Message );
                }
            }

            return true;
        }
Exemple #26
0
        public void Connect()
        {
            lock (_lock)
            {
                if (Connected) return;
                var connectEndEvent = new ManualResetEvent(false);
                _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

                _socket.BeginConnect(_config.GatewayIp, _config.GatewayPort, delegate(IAsyncResult result)
                {
                    try
                    {
                        var socket = (Socket)result.AsyncState;
                        socket.EndConnect(result);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Unbale to connect, error: {0}.", ex);
                    }
                    connectEndEvent.Set();
                }, _socket);

                if (connectEndEvent.WaitOne(10000) && Connected)
                {
                    _state.Size = CmppConstants.HeaderSize;
                    _state.PackageType = typeof(CmppHead);
                    _state.Header = null;
                    return;
                }

                Console.WriteLine("Fail to connect to remote host {0}:{1}", _config.GatewayIp, _config.GatewayPort);
                Disconnect();
            }
        }
Exemple #27
0
        public PooledSocket(SocketPool socketPool, IPEndPoint endPoint, int sendReceiveTimeout, int connectTimeout)
        {
            this.socketPool = socketPool;
            Created = DateTime.Now;

            //Set up the socket.
            socket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, sendReceiveTimeout);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, sendReceiveTimeout);
            socket.ReceiveTimeout = sendReceiveTimeout;
            socket.SendTimeout = sendReceiveTimeout;

            //Do not use Nagle's Algorithm
            socket.NoDelay = true;

            //Establish connection asynchronously to enable connect timeout.
            IAsyncResult result = socket.BeginConnect(endPoint, null, null);
            bool success = result.AsyncWaitHandle.WaitOne(connectTimeout, false);
            if (!success) {
                try { socket.Close(); } catch { }
                throw new SocketException();
            }
            socket.EndConnect(result);

            //Wraps two layers of streams around the socket for communication.
            stream = new BufferedStream(new NetworkStream(socket, false));
        }
Exemple #28
0
        private void Client_Load(object sender, EventArgs e)
        {
            Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp);

            // Start connecting on load
            IAsyncResult result = socket.BeginConnect("cse3461-server.cloudapp.net", 34567, null, null);

            // Wait up to 5 seconds
            bool success = result.AsyncWaitHandle.WaitOne(5000, true);

            // Exit if failed
            if (!success)
            {
                socket.Close();

                MessageBox.Show("Unable to Connect", "Unable to connect", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
                return;
            }

            // success, so create a transceiver and hook up events
            _xcvr = new MessageXcvr(socket);
            _xcvr.Disconnected += _xcvr_Disconnected;
            _xcvr.MessageReceived += _xcvr_MessageReceived;
        }
            public void StartClient()
            {
                try
                {
                    IPHostEntry ipHostInfo = Dns.GetHostEntry("localhost");
                    IPAddress ipAddress = ipHostInfo.AddressList[0];
                    IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);

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

                    client.BeginConnect(remoteEP,
                        new AsyncCallback(ConnectCallback), client);
                    connectDone.WaitOne();

                    Send(client, Message);
                    sendDone.WaitOne();

                    Receive(client);
                    receiveDone.WaitOne();

                    mainStr += "Response received : " + response + "\n";

                    client.Shutdown(SocketShutdown.Both);
                    client.Close();

                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }
Exemple #30
0
        public void connect(String Ip, UInt16 port)
        {
            // Connect to a remote device.

            // Establish the remote endpoint for the socket.
            // The name of the remote device is Ip.
            //Change to these 2 line for Dns resolve
            //IPHostEntry ipHostInfo = Dns.GetHostEntry(Ip);
            //IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPAddress ipAddress = IPAddress.Parse(Ip);
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

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

            // Connect to the remote endpoint.
            tcpClientSocket.BeginConnect(remoteEP,
                new AsyncCallback(connectCallback), tcpClientSocket);
            connectDone.WaitOne(6000);

            // Receive the response from the remote device.

            // receiveDone.WaitOne();

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

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

            receive(tcpClientSocket);
        }
        public void StartListening()
        {
            byte[] bytes = new Byte[BufferSize];

            IPHostEntry ipHostInfo = new IPHostEntry();
            ipHostInfo.AddressList = new IPAddress[] { _serverIP};
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint remoteEndPoint = new IPEndPoint(ipAddress, port);
            // Create a TCP/IP socket.
            Socket listener = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);

            try
            {
                listener.BeginConnect(remoteEndPoint, new AsyncCallback(ConnectCallback), listener);
                connectDone.WaitOne();

                // receive data
                receiveDone.Reset();
                Receive(listener);
                receiveDone.WaitOne();

                Console.WriteLine("Disconnecting from feed");

                listener.Shutdown(SocketShutdown.Both);
                listener.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Feed Error " + e.ToString());
            }
        }
Exemple #32
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                IPAddress ipAddress = IPAddress.Parse(txtServerIP.Text);
                //Server is listening on port
                IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, Convert.ToInt32(txtPort.Text));

                //Connect to the server
                clientSocket.BeginConnect(ipEndPoint, new AsyncCallback(OnConnect), null);

                byteData = new byte[1024];
                //Start listening to the data asynchronously
                clientSocket.BeginReceive(byteData,
                                           0,
                                           byteData.Length,
                                           SocketFlags.None,
                                           new AsyncCallback(OnReceive),
                                           null);
                btnOK.Enabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "ChatClient", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public override bool Create()
        {
            {
                try
                {
                    // Close the socket if it is still open
                    if (m_sock != null && m_sock.Connected)
                        return true;

                    // Create the socket object
                    m_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                    // Define the Server address and port                    
                    IPEndPoint epServer = new IPEndPoint(IPAddress.Parse(m_szIP), m_iPort);

                    // Connect to the server blocking method and setup callback for recieved data
                    // m_sock.Connect( epServer );
                    // SetupRecieveCallback( m_sock );

                    // Connect to server non-Blocking method
                    m_sock.Blocking = false;
                    AsyncCallback onconnect = new AsyncCallback(OnConnect);
                    m_sock.BeginConnect(epServer, onconnect, m_sock);

                    return true;
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message, "Server Connect failed!");
                    return false;
                }
            }
        }
        public void Start()
        {
            try
            {
                // TODO async resolving
                IPAddress ipAddress;
                bool parsed = IPAddress.TryParse(config.server, out ipAddress);
                if (!parsed)
                {
                    IPHostEntry ipHostInfo = Dns.GetHostEntry(config.server);
                    ipAddress = ipHostInfo.AddressList[0];
                }
                IPEndPoint remoteEP = new IPEndPoint(ipAddress, config.server_port);

                remote = new Socket(ipAddress.AddressFamily,
                    SocketType.Stream, ProtocolType.Tcp);

                // Connect to the remote endpoint.
                remote.BeginConnect(remoteEP,
                    new AsyncCallback(connectCallback), null);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                this.Close();
            }
        }
		public void Connect(string hostname, int port)
		{
			// Connect to a remote device.
			try 
			{
				// Establish the remote endpoint for the socket.
				IPHostEntry ipHostInfo = Dns.Resolve(hostname);
				IPAddress ipAddress = ipHostInfo.AddressList[0];
				IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

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

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

			} 
			catch (Exception e) 
			{
				m_lasterror = e.Message;
				ErrorNotify("DataAsyncSocket.Connect");
			}
		}
        public static IEnumerable<int> Scan(string ip, int startPort, int endPort)
        {
            openPorts.Clear();
            //List<int> openPorts = new List<int>();

            for (int port = startPort; port <= endPort; port++)
            {
                Debug.WriteLine(string.Format("Scanning port {0}", port));
                Socket scanSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

                try
                {
                    //scanSocket.Connect(new IPEndPoint(IPAddress.Parse(ip), port));
                    //scanSocket.Disconnect(false);
                    //openPorts.Add(port);
                    //scanSocket.BeginConnect(new IPEndPoint(ip, port), ScanCallBack, new ArrayList() { scanSocket, port });
                    scanSocket.BeginConnect(new IPEndPoint(IPAddress.Parse(ip), port), ScanCallBack, new ArrayList() { scanSocket, port });
                }
                catch (Exception ex)
                {
                    //bury exception since it means we could not connect to the port
                }

            }
            //Computers.comp1.Add(ip, openPorts);
            return openPorts;
        }
        public void Connect(string message)
        {
            // Connect to a remote device.
            try
            {
                var ipHostInfo = Dns.Resolve(Dns.GetHostName());
                IPAddress ipAddress = ipHostInfo.AddressList[0];
                IPEndPoint remoteEP = new IPEndPoint(ipAddress, 12000);

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

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

                // Send test data to the remote device.
                Send(client, message);
                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)
            {
                Console.WriteLine(e.ToString());
            }
        }
Exemple #38
0
    public void Connect()
    {
        try
        {
            // Do nothing if connected
            if (m_sock != null && m_sock.Connected)
            {
                return;
            }

            // Try to connect
            m_sock = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // TODO: Input check
            m_server_ip   = ip_entry.Text;
            m_server_port = Convert.ToInt16(port_entry.Text);

            // Define the Server address and port
            IPEndPoint epServer = new IPEndPoint(IPAddress.Parse(m_server_ip), m_server_port);

            // Connect to server non-Blocking method
            m_sock.Blocking = false;
            m_sock.BeginConnect(epServer, new AsyncCallback(OnConnected), m_sock);
        }
        catch (Exception e)
        {
            WriteLog("Unable to connect to " + m_server_ip + ":" + m_server_port + "\n", tagInfo);
        }
    }
Exemple #39
0
        /// <summary>
        /// ConnectToServer
        /// </summary>
        /// <returns></returns>
        private bool SyncConnectToServer()
        {
            System.Net.Sockets.Socket socketClient = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            connectDone.Reset();
            socketClient.BeginConnect(locEndpoint, new AsyncCallback(AsyncConnectCallback), socketClient);
            connectDone.WaitOne();

            return(socketClient == null ? false : socketClient.Connected);
        }
 /// <summary>
 /// 开启客户端socket
 /// </summary>
 public static void ClientSocketStarting(SocketConnectConfig sktconfig)
 {
     Sktconfig = sktconfig;
     if (ServerSocketEndPoint != null && (SocketClient == null || !SocketClient.Connected))
     {
         SocketClient           = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
         SocketClientConnection = new SocketConnectionReConnectClient(SocketClient);
         SocketClient.BeginConnect(ServerSocketEndPoint, ConnectCallback, SocketClientConnection);
     }
 }
Exemple #41
0
 public void Connect(string ip, int port, int timeout = 5000)
 {
     try
     {
         if (IsConnect())
             return;
         this.ip = ip;
         this.port = port;
         _remoteEP = new IPEndPoint(IPAddress.Parse(ip), port);
         if (_stateObject.Socket == null)
         {
             System.Net.Sockets.Socket handler = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
             IAsyncResult asyncResult = handler.BeginConnect(_remoteEP, null, null);
             if (asyncResult.AsyncWaitHandle.WaitOne(timeout, true))
             {
                 handler.EndConnect(asyncResult);
                 _stateObject.Socket = handler;
                 var option = new TcpKeepAlive
                 {
                     OnOff = 1,
                     KeepAliveTime = 5000,
                     KeepAliveInterval = 1000
                 };
                 _stateObject.Socket.IOControl(IOControlCode.KeepAliveValues, option.GetBytes(), null);
                 BeginReceive(_ioEvent);
                 OnConnected(_stateObject);
             }
             else
             {
                 _stateObject.Init();
                 throw new SocketException(10060);
             }
         }
         else
         {
             _stateObject.Init();
         }
     }
     catch (ArgumentNullException arg)
     {
         throw new Exception.Exception(arg.Message);
     }
     catch (SocketException se)
     {
         throw new Exception.Exception(se.Message);
     }
     catch (System.Exception e)
     {
         throw new Exception.Exception(e.Message);
     }
 }
Exemple #42
0
 public void Connect(EndPoint endPoint)
 {
     ConnectingEvent();
     try
     {
         Socket = new System.Net.Sockets.Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
         Socket.BeginConnect(endPoint, ConnectCallback, Socket);
     }
     catch (Exception e)
     {
         ExceptionEvent(e);
         return;
     }
 }
 /// <summary>
 /// Will create a local socket and try to connect remote socket with specific ipendpoint
 /// </summary>
 /// <param name="IP"></param>
 /// <param name="Port"></param>
 public void Connect(string IP, int Port)
 {
     try
     {
         Socket connectorSock = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
         connectorSock.BeginConnect(new IPEndPoint(IPAddress.Parse(IP), Port), new AsyncCallback(outgoingConnect), connectorSock);
         this.LocalSockets.Add(connectorSock);
         this.ChannelLog?.Invoke(ChannelLogTypes.ConnectionStarted, "Client connection started to outgoing socket " + IP + ":" + Port);
     }
     catch (Exception ex)
     {
         this.ChannelError?.Invoke(ChannelErrorTypes.ConnectError, ex.Message.ToString(), ex, null);
     }
 }
Exemple #44
0
 void StartConnectingSocket(IPAddress addr, int port)
 {
     socket = new System.Net.Sockets.Socket(addr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
     try {
         socket.BeginConnect(addr, port, (ar) => {
             try {
                 socket.EndConnect(ar);
                 loop.NonBlockInvoke(connectedCallback);
             } catch {
             }
         }, null);
     } catch {
     }
 }
Exemple #45
0
        /// <summary>
        /// Connects the specified socket.
        /// </summary>
        /// <param name="socket">The socket.</param>
        /// <param name="endpoint">The IP endpoint.</param>
        /// <param name="timeout">The timeout.</param>
        public static void Connect(this System.Net.Sockets.Socket socket, EndPoint endpoint, TimeSpan timeout)
        {
            var result = socket.BeginConnect(endpoint, null, null);

            bool success = result.AsyncWaitHandle.WaitOne(timeout, true);

            if (success)
            {
                socket.EndConnect(result);
            }
            else
            {
                socket.Close();
                throw new SocketException(10060); // Connection timed out.
            }
        }
Exemple #46
0
        public static void Connect(this System.Net.Sockets.Socket socket, EndPoint endpoint, int timeout)
        {
            var result = socket.BeginConnect(endpoint, null, null);

            bool success = result.AsyncWaitHandle.WaitOne(timeout, true);

            if (socket.Connected)
            {
                socket.EndConnect(result);
            }
            else
            {
                socket.Close();
                throw new SocketException(ConnectionTimedOutStatusCode);
            }
        }
Exemple #47
0
        public void Open()
        {
            var  result  = _clientSocket.BeginConnect(IPAddress.Parse(_remoteIp), _remotePort, null, null);
            bool success = result.AsyncWaitHandle.WaitOne(5000, true);

            if (_clientSocket.Connected)
            {
                _clientSocket.EndConnect(result);
            }
            else
            {
                _clientSocket.Close();
                throw new SocketException(10060);
            }
            //_clientSocket.Connect(IPAddress.Parse(_remoteIp), _remotePort);
        }
Exemple #48
0
 void StartConnectingSocket(IPAddress addr, int port)
 {
     socket = new System.Net.Sockets.Socket(addr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
     try {
         socket.BeginConnect(addr, port, (ar) => {
             Enqueue(delegate {
                 try {
                     socket.EndConnect(ar);
                     connectedCallback();
                 } catch {
                 }
             });
         }, null);
     } catch {
     }
 }
Exemple #49
0
        /// <summary>
        /// 开始连接服务器
        /// </summary>
        /// <param name="port"></param>
        /// <param name="ip"></param>
        public void StartConnect(int port, string ip = "127.0.0.1")
        {
            try
            {
                mySocket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress  address  = IPAddress.Parse(ip);
                IPEndPoint endPoint = new IPEndPoint(address, port);

                //开始异步连接
                mySocket.BeginConnect(endPoint, asyncResult =>
                {
                    try
                    {
                        mySocket.EndConnect(asyncResult);                        //结束异步连接
                        // localEndPointIp = mySocket.LocalEndPoint.ToString();     //得到ip地址

                        OnSuccess?.Invoke(this);   //连接成功的回调

                        recThread = new Thread(RecMsg);
                        recThread.IsBackground = true;
                        recThread.Start(mySocket);


                        Task.Run(() =>
                        {
                            while (true)
                            {
                                if (mySocket != null && IsReceive)
                                {
                                    string ss = EndPointIp;
                                    SendMsg("hear," + ss);
                                }
                                Thread.Sleep(HeartbeatCheckInterval);
                            }
                        });
                    }
                    catch (Exception ex)
                    {
                        OnError?.Invoke(ex);
                    }
                }, null);
            }
            catch (Exception ex)
            {
                OnError?.Invoke(ex);    //报错的回调
            }
        }
Exemple #50
0
 /// <summary>
 /// Connect to server
 /// </summary>
 public void Connect(IPEndPoint iep)
 {
     lock (_locker)
     {
         AssertThat.IsFalse(IsConnected, "Already Connected");
         AssertThat.IsNotNull(iep, "iep is null");
         ConnectingEvent();
         try
         {
             Socket = new System.Net.Sockets.Socket(iep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
         }
         catch (Exception e)
         {
             throw new Exception(e.ToString());
         }
         try
         {
             Socket.BeginConnect(iep, delegate(IAsyncResult ar)
             {
                 try
                 {
                     var socket = ar.AsyncState as System.Net.Sockets.Socket;
                     AssertThat.IsNotNull(socket, "Socket is null when end connect");
                     socket.EndConnect(ar);
                     if (IsConnected)
                     {
                         ConnectedEvent();
                         Receive();
                     }
                     else
                     {
                         AssertThat.Fail("Connect faild");
                     }
                 }
                 catch (Exception e)
                 {
                     throw new Exception(e.ToString());
                 }
             }, Socket);
         }
         catch (Exception e)
         {
             throw new Exception(e.ToString());
         }
     }
 }
Exemple #51
0
        /// <summary>
        /// Connects the socket to the endpoint
        /// </summary>
        /// <exception cref="Exception">Socket already bound or connected</exception>
        public void Connect()
        {
            if (_socket.IsBound || _socket.Connected)
            {
                throw new Exception("Unable to connect. Socket already bound or connected.");
            }

            try
            {
                CreateEndPoint();
                _socket.BeginConnect(IpEndPoint, OnConnectCallback, _socket);
                _connectedEvent.WaitOne();
            }
            catch (Exception e)
            {
                throw new Exception("Couldn't connect.\n" + e.Message);
            }
        }
Exemple #52
0
        /// <summary>
        /// 异步连接服务器
        /// </summary>
        public virtual bool Connect()
        {
            if (IsConnection)
            {
                return(true);
            }
            //判断是否设置服务器IP地址,和端口
            if (string.IsNullOrEmpty(this.Ip))
            {
                CutConnection("服务器IP地址为空");
                return(false);
            }
            if (this.Port == 0)
            {
                CutConnection("服务器IP服务器端口为空");
                return(false);
            }
            try
            {
                //实例化Socket通讯对象
                sock = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                //生成一个网络端口
                IPEndPoint iep = new IPEndPoint(IPAddress.Parse(this.Ip), this.Port);
                //开始异步请求连接
                sock.BeginConnect(iep, new AsyncCallback(Connected), sock);
            }
            catch (SocketException ex)
            {
                //服务器断开
                CutConnection(ex.Message);
            }
            catch (ObjectDisposedException ex)
            {
                //服务器断开
                CutConnection(ex.Message);
            }
            catch (Exception ex)
            {
                //服务器断开
                CutConnection(ex.Message);
            }
            return(false);
        }
Exemple #53
0
        public int StartClient(string ipv4Add)
        {
            // Connect to a remote device.
            int connectionPort = Utils.getUnusedPort(PORT_START, PORT_END);

            try
            {
                // Establish the remote endpoint for the socket.
                // The name of the
                IPHostEntry ipHostInfo = Dns.GetHostEntry(ipv4Add);
                IPAddress   ipAddress  = ipHostInfo.AddressList[0];
                IPEndPoint  remoteEP   = new IPEndPoint(ipAddress, connectionPort);

                // Create a TCP/IP socket.
                System.Net.Sockets.Socket client = new System.Net.Sockets.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();

                // 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());
            }

            return(connectionPort);
        }
        /// <summary>
        /// Setup connection to server.
        /// </summary>
        /// <param name="host"></param>
        /// <param name="port"></param>
        /// <returns></returns>
        public System.Net.Sockets.Socket Connect(string host, int port)
        {
            // Establish the remote endpoint for the socket.
            // The name of the
            // remote device is "host.contoso.com".
            IPHostEntry ipHostInfo = Dns.GetHostEntry(host);
            IPAddress   ipAddress  = ipHostInfo.AddressList[0];
            IPEndPoint  remoteEP   = new IPEndPoint(ipAddress, port);

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

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

            return(client);
        }
Exemple #55
0
        private 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(ip);
                IPAddress   ipAddress  = ipHostInfo.AddressList[0];
                IPEndPoint  remoteEP   = new IPEndPoint(ipAddress, this.port);

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

                // Connect to the remote endpoint.


                IAsyncResult result = client.BeginConnect(remoteEP,
                                                          new AsyncCallback(ConnectCallback), client);

                bool success = result.AsyncWaitHandle.WaitOne(5000, true);

                if (!success)
                {
                    // NOTE, MUST CLOSE THE SOCKET

                    this.client.Close();
                    Debug.Log("Failed to connect server.");
                    throw new ApplicationException("Failed to connect server.");
                }
            }
            catch (Exception e)
            {
                Debug.Log(e.ToString());
            }
        }
        public void ConnectToServer()
        {
            // create the TcpListener which will listen for and accept new client connections asynchronously
            cClientSocket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            // convert the server address and port into an ipendpoint
            IPAddress[] mHostAddresses = Dns.GetHostAddresses(cServerAddress);
            IPEndPoint  mEndPoint      = null;

            foreach (IPAddress mHostAddress in mHostAddresses)
            {
                if (mHostAddress.AddressFamily == AddressFamily.InterNetwork)
                {
                    mEndPoint = new IPEndPoint(mHostAddress, cServerPort);
                }
            }

            // connect to server async
            try {
                cClientSocket.BeginConnect(mEndPoint, new AsyncCallback(ConnectToServerCompleted), new SocketGlobals.AsyncSendState(cClientSocket));
            } catch (Exception ex) {
                MessageBox.Show("ConnectToServer error: " + ex.Message);
            }
        }
Exemple #57
0
 System.IAsyncResult Utils.Wrappers.Interfaces.ISocket.BeginConnect(System.Net.EndPoint remoteEP, System.AsyncCallback callback, object state)
 {
     return(InternalSocket.BeginConnect(remoteEP, callback, state));
 }
    IEnumerator RestoreUpdate()
    {
        if (Application.internetReachability == NetworkReachability.NotReachable)
        {
            Log.LogInfo("connect time out");
            MainLoader.ChangeStep(LoadStep.NotNeedUpdate);
            yield break;
        }
        else if (Application.internetReachability == NetworkReachability.ReachableViaCarrierDataNetwork)
        {
            //3G Tip
        }
        //Restore DownLoad From Progress.xml
        System.Net.Sockets.Socket         sClient     = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.IP);
        System.Net.EndPoint               server      = new System.Net.IPEndPoint(Dns.GetHostAddresses(GameData.Domain)[0], System.Convert.ToInt32(strPort));
        System.Threading.ManualResetEvent connectDone = new System.Threading.ManualResetEvent(false);
        try
        {
            connectDone.Reset();
            sClient.BeginConnect(server, delegate(IAsyncResult ar) {
                try
                {
                    System.Net.Sockets.Socket client = (System.Net.Sockets.Socket)ar.AsyncState;
                    client.EndConnect(ar);
                }
                catch (System.Exception e)
                {
                    Log.LogInfo(e.Message + "|" + e.StackTrace);
                }
                finally
                {
                    connectDone.Set();
                }
            }
                                 , sClient);
            //timeout
            if (!connectDone.WaitOne(2000))
            {
                Log.LogInfo("connect time out");
                MainLoader.ChangeStep(LoadStep.CannotConnect);
                yield break;
            }
            else
            {
                if (!sClient.Connected)
                {
                    Log.LogInfo("connect disabled by server");
                    MainLoader.ChangeStep(LoadStep.CannotConnect);
                    yield break;
                }
            }
        }
        catch
        {
            sClient.Close();
            MainLoader.ChangeStep(LoadStep.CannotConnect);
            yield break;
        }
        finally
        {
            connectDone.Close();
        }
        //Log.LogInfo("download:" + string.Format(strVFile, strHost, strPort, strProjectUrl, strPlatform, strVFileName));
        using (WWW vFile = new WWW(string.Format(strVFile, strHost, strPort, strProjectUrl, strPlatform, strVFileName)))
        {
            //Log.LogInfo("error:" + vFile.error);
            yield return(vFile);

            if (vFile.error != null && vFile.error.Length != 0)
            {
                //Log.LogInfo("error " + vFile.error);
                vFile.Dispose();
                //not have new version file
                //can continue game
                MainLoader.ChangeStep(LoadStep.NotNeedUpdate);
                yield break;
            }
            if (vFile.bytes != null && vFile.bytes.Length != 0)
            {
                File.WriteAllBytes(strUpdatePath + "/" + "v.zip", vFile.bytes);
                DeCompressFile(strUpdatePath + "/" + "v.zip", strUpdatePath + "/" + "v.xml");
                vFile.Dispose();
            }
            else
            {
                MainLoader.ChangeStep(LoadStep.NotNeedUpdate);
                yield break;
            }
        }

        XmlDocument xmlVer = new XmlDocument();

        xmlVer.Load(strUpdatePath + "/" + "v.xml");
        XmlElement ServerVer = xmlVer.DocumentElement;

        if (ServerVer != null)
        {
            string strServer = ServerVer.GetAttribute("ServerV");
            UpdateClient = HttpManager.AllocClient(string.Format(strDirectoryBase, strHost, strPort, strProjectUrl, strPlatform, strServer, ""));
            //if (strServer != null && GameData.Version().CompareTo(strServer) == -1)
            //{
            //	strServerVer = strServer;
            //	foreach (XmlElement item in ServerVer)
            //	{
            //		string strClientV = item.GetAttribute("ClientV");
            //		if (strClientV == GameData.Version())
            //		{
            //			strUpdateFile = item.GetAttribute("File");
            //			break;
            //		}
            //	}

            //	if (strUpdateFile != null && strUpdateFile.Length != 0)
            //		StartCoroutine("DownloadNecessaryData");
            //}
            //else
            //{
            //	Log.LogInfo("not need update");
            //             MainLoader.ChangeStep(LoadStep.NotNeedUpdate);
            //}
        }
    }
Exemple #59
0
    protected void OnBoopBtnClicked(object sender, EventArgs e)
    {
        //TODO: Check network connection

        try
        {
            //Fastest check first.
            if (!FilesToBoop.Any())
            {
                //TODO: Throw error
                return;
            }

            if (NetUtils.Validate(targetIP.Text) == false)
            {
                //TODO: Throw error
                return;
            }

            string DSip       = targetIP.Text;
            int    ServerPort = Int32.Parse(Port.Text);

            // THE FIREWALL IS NO LONGER POKED!
            // THE SNEK IS FREE FROM THE HTTPLISTENER TIRANY!

            // setStatusLabel("Opening the new and improved snek server...");
            //   enableControls(false);
            Console.WriteLine("Active Dir");
            Console.WriteLine(ActiveDir);
            Console.WriteLine("Port");
            Console.WriteLine(ServerPort.ToString());
            string SafeDir = ActiveDir + "/";


            HTTPServer = new MyServer(ServerPort, ActiveDir);
            HTTPServer.Start();


            System.Threading.Thread.Sleep(100);

            //  setStatusLabel("Opening socket to send the file list...");

            s = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            IAsyncResult result = s.BeginConnect(DSip, 5000, null, null);
            result.AsyncWaitHandle.WaitOne(5000, true);

            if (!s.Connected)
            {
                s.Close();
                HTTPServer.Stop();
                //  MessageBox.Show("Failed to connect to 3DS" + Environment.NewLine + "Please check:" + Environment.NewLine + "Did you write the right IP adress?" + Environment.NewLine + "Is FBI open and listening?", "Connection failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //   lblIPMarker.Visible = true;
                //    setStatusLabel("Ready");
                //    enableControls(true);
                return;
            }

            //  setStatusLabel("Sending the file list...");

            String message       = "";
            String formattedPort = ":" + Port.Text + "/";

            foreach (var CIA in FilesToBoop)
            {
                message += NetUtils.GetLocalIPAddress() + formattedPort + System.Web.HttpUtility.UrlEncode(System.IO.Path.GetFileName(CIA)) + "\n";
            }

            //boop the info to the 3ds...
            byte[] Largo  = BitConverter.GetBytes((uint)Encoding.ASCII.GetBytes(message).Length);
            byte[] Adress = Encoding.ASCII.GetBytes(message);

            Array.Reverse(Largo);     //Endian fix

            s.Send(AppendTwoByteArrays(Largo, Adress));

            // setStatusLabel("Booping files... Please wait");
            s.BeginReceive(new byte[1], 0, 1, 0, new AsyncCallback(GotData), null);     //Call me back when the 3ds says something.

            //#if DEBUG
        }
        catch (Exception ex)
        {
            //Hopefully, some day we can have all the different exceptions handled... One can dream, right? *-*
            //   MessageBox.Show("Something went really wrong: " + Environment.NewLine + Environment.NewLine + "\"" + ex.Message + "\"" + Environment.NewLine + Environment.NewLine + "If this keeps happening, please take a screenshot of this message and post it on our github." + Environment.NewLine + Environment.NewLine + "The program will close now", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            Application.Quit();
        }
        //#endif
    }
Exemple #60
0
 public void ConnectAsync(IPAddress addr, int port)
 {
     _tcpSock.BeginConnect(new IPEndPoint(addr, port), EndConnect, _tcpSock);
 }