Exemple #1
0
        public static void AcceptCallback(IAsyncResult ar)
        {
            // Get the socket that handles the client request.
            //Socket listener = (Socket) ar.AsyncState;
            //Socket handler = listener.EndAccept(ar);	// hander.RemoveEndPoint にリモートEPの情報が入っている
            AcceptStateObject acceptState = ar.AsyncState as AcceptStateObject;
            Socket            listener    = acceptState.Listener;
            Socket            handler     = listener.EndAccept(ar);

            acceptState.Accepted = (handler.RemoteEndPoint as IPEndPoint).Address.ToString();

            // Signal the main thread to continue.
            acceptDone.Set();

            // Create the state object.
            StateObject state = new StateObject();

            state.workSocket = handler;
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                                 new AsyncCallback(ReadCallback), state);
        }
Exemple #2
0
        private static void DoAcceptSocketCallback(IAsyncResult ar)
        {
            AcceptStateObject state    = ar.AsyncState as AcceptStateObject;
            TcpListener       listener = state.Listener;

            try {
                Socket socket = listener.EndAcceptSocket(ar);
                byte[] bytes  = new byte[socket.Available];
                socket.Receive(bytes);
                string msg = System.Text.Encoding.UTF8.GetString(bytes);
                if (msg == "ACK")
                {
                    var remoteEP = socket.RemoteEndPoint as IPEndPoint;
                    state.AcceptedAddress = remoteEP.Address.ToString();
                    _tcpClientConnected.Set();
                }
                socket.Close();
            } catch (Exception e) {
                System.Diagnostics.Debug.WriteLine(e.Message);
            }
        }
Exemple #3
0
        public IEnumerable <string> StartListening(int portNo)
        {
            IPEndPoint localEP = new IPEndPoint(IPAddress.Any, portNo);

            Console.WriteLine($"Local address and port : {localEP.ToString()}");
            List <string> connectedList = new List <string>();
            Socket        listener      = new Socket(localEP.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            var           start         = DateTime.Now;

            try {
                listener.Bind(localEP);
                listener.Listen(128);
                TimeSpan ts = DateTime.Now - start;
                while (ts.Seconds < 5)
                {
                    acceptDone.Reset();
                    Console.WriteLine("Waiting for a connection..." + ts.Seconds.ToString());
                    var state = new AcceptStateObject()
                    {
                        Listener = listener,
                    };
                    var ar = listener.BeginAccept(new AsyncCallback(AcceptCallback), state);
                    if (acceptDone.WaitOne(1000))
                    {
                        connectedList.Add(state.Accepted);
                    }
                    ts = DateTime.Now - start;
                }
            } catch (Exception e) {
                Console.WriteLine(e.ToString());
            }
            // アドレスの第4オクテットの昇順でソート
            return(connectedList.OrderBy(adrs => {
                int idx = adrs.LastIndexOf('.');
                int adrs4th = int.Parse(adrs.Substring(idx + 1));
                return adrs4th;
            }));
        }
Exemple #4
0
        // Process the client connection.
        private static void DoAcceptTcpClientCallback(IAsyncResult ar)
        {
            AcceptStateObject state    = ar.AsyncState as AcceptStateObject;
            TcpListener       listener = state.Listener;

            try {
                TcpClient client = listener.EndAcceptTcpClient(ar);
                System.Threading.Thread.Sleep(_waitTime2);
                NetworkStream ms    = client.GetStream();
                byte[]        bytes = new byte[client.Available];
                ms.Read(bytes, 0, client.Available);
                string msg = System.Text.Encoding.UTF8.GetString(bytes);
                //System.Diagnostics.Debug.WriteLine( "{0}, {1}", msg.Length, msg );
                if (msg == "ACK")
                {
                    var remoteEP = client.Client.RemoteEndPoint as IPEndPoint;
                    state.AcceptedAddress = remoteEP.Address.ToString();
                    _tcpClientConnected.Set();
                }
                client.Close();
            } catch (Exception e) {
                System.Diagnostics.Debug.WriteLine(e.Message);
            }
        }
Exemple #5
0
        // Accept one client connection asynchronously.
        public IEnumerable <string> StartListening(string localHostIP, int portNo)
        {
            TcpListener listener = new TcpListener(IPAddress.Parse(localHostIP), portNo);
            //TcpListener listener = new TcpListener( IPAddress.Any, portNo );
            List <string> connectedList = new List <string>();

            try {
                listener.Start();
#if true
                do
                {
                    var state = new AcceptStateObject()
                    {
                        Listener        = listener,
                        AcceptedAddress = string.Empty,
                    };
                    _tcpClientConnected.Reset();
                    var acceptDone = listener.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpClientCallback), state);
                    if (_tcpClientConnected.WaitOne(_waitTime1))
                    {
                        connectedList.Add(state.AcceptedAddress);
                        //System.Diagnostics.Debug.WriteLine( state.AcceptedAddress );
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("TIMEOUT");
                        break;
                    }
                    //System.Threading.Thread.Sleep( _waitTime2 );
                } while (listener.Pending());
#else
                while (true)
                {
                    var state = new AcceptStateObject()
                    {
                        Listener        = listener,
                        AcceptedAddress = string.Empty,
                    };
                    _tcpClientConnected.Reset();
                    var acceptDone = listener.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpClientCallback), state);
                    if (_tcpClientConnected.WaitOne(_waitTime1))
                    {
                        connectedList.Add(state.AcceptedAddress);
                    }
                    else
                    {
                        System.Threading.Thread.Sleep(_waitTime2);
                        if (listener.Pending() == false)
                        {
                            System.Diagnostics.Debug.WriteLine("TIMEOUT");
                            break;
                        }
                    }
                }
#endif
            } catch (Exception e) {
                System.Diagnostics.Debug.WriteLine(e.Message);
            } finally {
                listener.Stop();
            }
            // アドレスの第4オクテットの昇順でソート
            return(connectedList.OrderBy(adrs =>
            {
                int idx = adrs.LastIndexOf('.');
                return int.Parse(adrs.Substring(idx + 1));
            }).Distinct());
        }