Esempio n. 1
0
        public static Socket ConnectTCPSocket(IPAddress addr, int port, int timeout)
        {
            Socket                s         = new Socket(addr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            IAsyncResult          ar        = null;
            bool                  timed_out = false;
            AsyncConnectProcessor proc      = new AsyncConnectProcessor(s);

            try {
                ar        = s.BeginConnect(new IPEndPoint(addr, port), new AsyncCallback(proc.End), null);
                timed_out = !ar.AsyncWaitHandle.WaitOne(timeout, false);
            }
            catch (Exception ex) { //ブロック中の例外はここで
                proc.EndConnectRequired = false;
                s.Close();
                ProtocolsPlugin.Instance.NetLog(ex.Message);
                return(null);
            }

            if (timed_out)
            {
                proc.EndConnectRequired = false;
                s.Close();
                ProtocolsPlugin.Instance.NetLog(String.Format("timed out connecting to {0}", addr.ToString()));
                return(null);
            }

            if (!s.Connected)
            {
                ProtocolsPlugin.Instance.NetLog(proc.ErrorMessage);
                return(null);
            }

            return(s);
        }
Esempio n. 2
0
        public static Socket ConnectTCPSocket(IPAddress addr, int port, int timeout)
        {
            Socket s = new Socket(addr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            s.NoDelay = true;
            IAsyncResult ar = null;
            bool timed_out = false;
            AsyncConnectProcessor proc = new AsyncConnectProcessor(s);

            try {
                ar = s.BeginConnect(new IPEndPoint(addr, port), new AsyncCallback(proc.End), null);
                timed_out = !ar.AsyncWaitHandle.WaitOne(timeout, false);
            }
            catch (Exception ex) { //ブロック中の例外はここで
                proc.EndConnectRequired = false;
                s.Close();
                ProtocolsPlugin.Instance.NetLog(ex.Message);
                return null;
            }

            if (timed_out) {
                proc.EndConnectRequired = false;
                s.Close();
                ProtocolsPlugin.Instance.NetLog(String.Format("timed out connecting to {0}", addr.ToString()));
                return null;
            }

            if (!s.Connected) {
                ProtocolsPlugin.Instance.NetLog(proc.ErrorMessage);
                return null;
            }

            return s;
        }