Esempio n. 1
0
        private void Accept()
        {
            m_acceptedSocket = AsyncSocket.Create(m_address.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            // start accepting socket async
            m_handle.Accept(m_acceptedSocket);
        }
Esempio n. 2
0
        /// <summary>
        /// Start listening for incoming connections.
        /// </summary>
        public void Start()
        {
            // Abort if already started
            if (_isStarted)
            {
                Logger.Debug("WifiRemote: ListenSocket already accepting connections, aborting start ...");
                return;
            }

            if (_listenSocket == null)
            {
                InitSocket();
            }

            Exception error;

            if (!_listenSocket.Accept(_port, out error))
            {
                Logger.Error("WifiRemote: Error starting server: " + error.Message);
                return;
            }

            _isStarted   = true;
            _loginTokens = new List <AutoLoginToken>();
            Logger.Info("WifiRemote: Now accepting connections");
        }
Esempio n. 3
0
        private void Accept()
        {
            m_acceptedSocket = new PgmSocket(m_options, PgmSocketType.Receiver, m_address);
            m_acceptedSocket.Init();

            m_handle.Accept(m_acceptedSocket.Handle);
        }
Esempio n. 4
0
        private void Accept()
        {
            m_acceptedSocket = new PgmSocket(m_options, PgmSocketType.Receiver, m_address);
            m_acceptedSocket.Init();

#pragma warning disable 618
            // TODO: we must upgrade to GetAcceptedSocket, need to be tested on Windows with MSMQ installed
            m_handle.Accept(m_acceptedSocket.Handle);
#pragma warning restore 618
        }
Esempio n. 5
0
        public void EnhancedSocket_Async_SendRecv()
        {
            AsyncSocket sockListen = null;
            AsyncSocket sock1      = null;
            AsyncSocket sock2      = null;
            int         cb;

            try
            {
                sockListen = new AsyncSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                sockListen.ListenOn(new IPEndPoint(IPAddress.Any, 45001));

                sock1 = new AsyncSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                sock1.Connect(new IPEndPoint(IPAddress.Loopback, 45001));

                sock2 = sockListen.Accept();

                for (int i = 0; i < 1000; i++)
                {
                    byte[] buf10 = new byte[10];
                    byte[] buf5  = new byte[5];

                    sock1.Send(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
                    cb = sock2.Receive(buf10);
                    Assert.AreEqual(10, cb);
                    CollectionAssert.AreEqual(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, buf10);

                    sock2.Send(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
                    cb = sock1.Receive(buf5);
                    Assert.AreEqual(5, cb);
                    CollectionAssert.AreEqual(new byte[] { 0, 1, 2, 3, 4 }, buf5);
                    cb = sock1.Receive(buf5);
                    Assert.AreEqual(5, cb);
                    CollectionAssert.AreEqual(new byte[] { 5, 6, 7, 8, 9 }, buf5);
                }
            }
            finally
            {
                if (sockListen != null)
                {
                    sockListen.Close();
                }

                if (sock1 != null)
                {
                    sock1.Close();
                }

                if (sock2 != null)
                {
                    sock2.Close();
                }
            }
        }
Esempio n. 6
0
        private void startStopButton_Click(object sender, EventArgs e)
        {
            if (!isStarted)
            {
                // Start the echo server
                UInt16 port;
                UInt16.TryParse(portTextBox.Text, out port);

                // AsyncSocket.Accept will setup sockets for IPv4 and IPv6
                // You can connect using telnet

                Exception error;
                if (!listenSocket.Accept(port, out error))
                {
                    LogError("Error starting server: {0}", error);
                    return;
                }

                LogInfo("Echo server started on port {0}", listenSocket.LocalPort);
                isStarted = true;

                portTextBox.Enabled  = false;
                startStopButton.Text = "Stop";
            }
            else
            {
                // Stop accepting connections
                listenSocket.Close();

#if IS_MULTITHREADED
                // Stop any client connections
                lock (connectedSockets)
                {
                    foreach (AsyncSocket socket in connectedSockets)
                    {
                        socket.Close();
                    }
                }
#else
                // Stop any client connections
                foreach (AsyncSocket socket in connectedSockets)
                {
                    socket.Close();
                }
#endif

                LogInfo("Stopped Echo server");
                isStarted = false;

                portTextBox.Enabled  = true;
                startStopButton.Text = "Start";
            }
        }
Esempio n. 7
0
        private void Accept()
        {
            //m_acceptedSocket = AsyncSocket.Create(m_address.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            // start accepting socket async
            m_handle.Accept();

            // Disable TIME_WAIT tcp state
            if (m_options.DisableTimeWait)
            {
                m_handle.LingerState = new LingerOption(true, 0);
            }
        }
        public void StartSocket()
        {
            listenSocket = new AsyncSocket();
            listenSocket.AllowMultithreadedCallbacks = true;
            listenSocket.DidAccept += new AsyncSocket.SocketDidAccept(listenSocket_DidAccept);
            Exception error;

            if (!listenSocket.Accept(ushort.Parse(Preferences.Instance.Value("port")), out error))
            {
                Logger.Instance.eventLog.WriteEntry(String.Format("Error starting server: {0}", error), EventLogEntryType.Information);
                return;
            }

            PublishBonjour();
        }
Esempio n. 9
0
        /// <summary>

        /// Starts the server

        /// </summary>

        /// <returns>

        /// <c>true</c> - if the server started successfully;

        /// <c>false</c> - the server failed to start. The <see cref="OnFailedToStart"/> event will be raised.

        /// </returns>

        public bool Start()

        {
            if (!this.isStarted)

            {
                Exception error;

                if (!listenSocket.Accept(this.port, out error))

                {
                    this.OnFailedToStart(this, EventArgs.Empty);

                    LogError("Error starting server: {0}", error);

                    return(false);
                }



                if (BonjourService.IsSupported)
                {
                    this.bonjour.Start(this.port);
                }



                this.socketCleanupTimer.Start();



                LogInfo("Growl server started on port {0}", listenSocket.LocalPort);

                isStarted = true;
            }

            return(true);
        }
Esempio n. 10
0
        static void Main(string[] args)
        {
            ForceDotNet.Force();

            CompletionPort completionPort = CompletionPort.Create();

            AutoResetEvent listenerEvent = new AutoResetEvent(false);
            AutoResetEvent clientEvent   = new AutoResetEvent(false);
            AutoResetEvent serverEvent   = new AutoResetEvent(false);

            AsyncSocket listener = AsyncSocket.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            completionPort.AssociateSocket(listener, listenerEvent);

            AsyncSocket server = AsyncSocket.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            completionPort.AssociateSocket(server, serverEvent);

            AsyncSocket client = AsyncSocket.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            completionPort.AssociateSocket(client, clientEvent);

            Task.Factory.StartNew(() =>
            {
                CompletionStatus [] completionStatuses = new CompletionStatus[10];

                int removed;

                while (true)
                {
                    var result = completionPort.GetMultipleQueuedCompletionStatus(-1, completionStatuses, out removed);

                    for (int i = 0; i < removed; i++)
                    {
                        var completionStatus = completionStatuses[i];

                        Console.WriteLine("{0} {1} {2}", completionStatus.SocketError, completionStatus.OperationType,
                                          completionStatus.BytesTransferred);

                        if (completionStatus.State != null)
                        {
                            AutoResetEvent resetEvent = (AutoResetEvent)completionStatus.State;
                            resetEvent.Set();
                        }
                    }

                    Console.WriteLine("Handled {0} statuses", removed);

                    Thread.Sleep(100);
                }
            });

            listener.Bind(IPAddress.Any, 5555);
            listener.Listen(1);

            //Console.WriteLine(listener.LocalEndPoint);

            client.Bind(IPAddress.Any, 0);
            client.Connect("localhost", 5555);

            ////Thread.Sleep(100);

            listener.Accept(server);

            listenerEvent.WaitOne();
            clientEvent.WaitOne();

            byte[] sendBuffer = new byte[1] {
                2
            };
            byte[] recvBuffer = new byte[1];

            server.Receive(recvBuffer);
            client.Send(sendBuffer);

            clientEvent.WaitOne();
            serverEvent.WaitOne();
            ////Console.WriteLine("server received");

            Console.ReadLine();
        }
Esempio n. 11
0
        public void Initialize(bool isServer = false)
        {
            NetCommonIO netIO = new NetCommonIO();

            netIO.Initialize(SelectorType.IOCP, 500);

            INetSelector selector = netIO.Selector();

            if (null != selector)
            {
                selector.RegAcceptedDelegate(PrintAcceptLog);
                selector.RegConnectedDelegate(PrintConnectedLog);
                selector.RegSentDelegate(PrintSentLog);
                selector.RegReceivedDelegate(PrintReceiveLog);
                selector.RegDisconnectedDelegate(PrintDisconnectedLog);
                selector.Start();

                if (!isServer)
                {
                    //client
                    List <ClientThreadT> client_threads = new List <ClientThreadT>();

                    Random rand = new Random(Guid.NewGuid().GetHashCode());
                    for (int i = 0; i < 100; ++i)
                    {
                        SelItem     clientItem   = new SelItem();
                        AsyncSocket clientSocket = AsyncSocket.CreateIPv4Tcp();
                        selector.AssociateSocket(clientSocket, clientItem);
                        clientSocket.Bind(IPAddress.Any, 0);
                        Console.WriteLine($"Client ip:{NetUtil.ToIportString(clientSocket.LocalEndPoint)}");

                        int           name   = rand.Next();
                        ClientThreadT thread = new ClientThreadT(clientSocket, clientItem, name.ToString());
                        client_threads.Add(thread);
                    }

                    Console.WriteLine("Wait client threads to be end ...");

                    bool finished = false;
                    while (!finished)
                    {
                        finished = true;
                        int count = 0;
                        foreach (var thread in client_threads)
                        {
                            ++count;
                            if (!thread.finished())
                            {
                                finished = false;
                                Thread.Sleep(50);
                                break;
                            }
                        }
                        if (finished)
                        {
                            break;
                        }
                    }

                    Console.WriteLine("Client threads all finished.");
                    selector.Stop();
                }
                else
                {
                    //server
                    try
                    {
                        SelItem     accept_item = new SelItem();
                        AsyncSocket listener    = AsyncSocket.CreateIPv4Tcp();
                        selector.AssociateSocket(listener, accept_item);
                        listener.Bind(IPAddress.Any, 56665);
                        listener.Listen(int.MaxValue);

                        Console.WriteLine("Server started :");

                        //begin to accept
                        while (true)
                        {
                            listener.Accept();
                            accept_item.Handle.WaitOne();

                            var     serverSocket = listener.GetAcceptedSocket();
                            SelItem server_item  = new SelItem();
                            selector.AssociateSocket(serverSocket, server_item);

                            NetData.ReceiveData(serverSocket);
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
            }
        }
Esempio n. 12
0
        public static void Main(string[] args)
        {
            CompletionPort completionPort = CompletionPort.Create();

            AutoResetEvent listenerEvent = new AutoResetEvent(false);
            AutoResetEvent clientEvent   = new AutoResetEvent(false);
            AutoResetEvent serverEvent   = new AutoResetEvent(false);

            AsyncSocket listener = AsyncSocket.Create(AddressFamily.InterNetwork,
                                                      SocketType.Stream, ProtocolType.Tcp);

            completionPort.AssociateSocket(listener, listenerEvent);

            AsyncSocket server = AsyncSocket.Create(AddressFamily.InterNetwork,
                                                    SocketType.Stream, ProtocolType.Tcp);

            completionPort.AssociateSocket(server, serverEvent);

            AsyncSocket client = AsyncSocket.Create(AddressFamily.InterNetwork,
                                                    SocketType.Stream, ProtocolType.Tcp);

            completionPort.AssociateSocket(client, clientEvent);

            Task.Factory.StartNew(() =>
            {
                CompletionStatus completionStatus;

                while (true)
                {
                    var result = completionPort.GetQueuedCompletionStatus(-1, out completionStatus);

                    if (result)
                    {
                        Console.WriteLine("{0} {1} {2}", completionStatus.SocketError,
                                          completionStatus.OperationType, completionStatus.BytesTransferred);

                        if (completionStatus.State != null)
                        {
                            AutoResetEvent resetEvent = (AutoResetEvent)completionStatus.State;
                            resetEvent.Set();
                        }
                    }
                }
            });

            listener.Bind(IPAddress.Any, 5555);
            listener.Listen(1);

            client.Connect("localhost", 5555);

            listener.Accept(server);


            listenerEvent.WaitOne();
            clientEvent.WaitOne();

            byte[] sendBuffer = new byte[1] {
                2
            };
            byte[] recvBuffer = new byte[1];

            client.Send(sendBuffer);
            server.Receive(recvBuffer);

            clientEvent.WaitOne();
            serverEvent.WaitOne();

            server.Dispose();
            client.Dispose();
            Console.ReadLine();
        }
Esempio n. 13
0
        public void SendReceive()
        {
            CompletionPort completionPort = CompletionPort.Create();

            bool exception = false;

            var task = Task.Factory.StartNew(() =>
            {
                bool cancel = false;

                while (!cancel)
                {
                    CompletionStatus [] completionStatuses = new CompletionStatus[10];

                    int removed;

                    completionPort.GetMultipleQueuedCompletionStatus(-1, completionStatuses, out removed);

                    for (int i = 0; i < removed; i++)
                    {
                        if (completionStatuses[i].OperationType == OperationType.Signal)
                        {
                            cancel = true;
                        }
                        else if (completionStatuses[i].SocketError == SocketError.Success)
                        {
                            EventWaitHandle manualResetEvent = (EventWaitHandle)completionStatuses[i].State;
                            manualResetEvent.Set();
                        }
                        else
                        {
                            exception = true;
                        }
                    }
                }
            });

            AutoResetEvent clientEvent   = new AutoResetEvent(false);
            AutoResetEvent acceptedEvent = new AutoResetEvent(false);

            AsyncSocket listener = AsyncSocket.CreateIPv4Tcp();

            completionPort.AssociateSocket(listener, acceptedEvent);
            listener.Bind(IPAddress.Any, 0);
            int port = listener.LocalEndPoint.Port;

            listener.Listen(1);

            listener.Accept();

            AsyncSocket clientSocket = AsyncSocket.CreateIPv4Tcp();

            completionPort.AssociateSocket(clientSocket, clientEvent);
            clientSocket.Bind(IPAddress.Any, 0);
            clientSocket.Connect("localhost", port);

            clientEvent.WaitOne();
            acceptedEvent.WaitOne();

            var serverSocket = listener.GetAcceptedSocket();

            AutoResetEvent serverEvent = new AutoResetEvent(false);

            completionPort.AssociateSocket(serverSocket, serverEvent);

            byte[] recv = new byte[1];
            serverSocket.Receive(recv);

            byte[] data = new[] { (byte)1 };

            clientSocket.Send(data);
            clientEvent.WaitOne(); // wait for data to be send

            serverEvent.WaitOne(); // wait for data to be received

            Assert.AreEqual(1, recv[0]);

            completionPort.Signal(null);
            task.Wait();

            Assert.IsFalse(exception);

            completionPort.Dispose();
            listener.Dispose();
            serverSocket.Dispose();
            clientSocket.Dispose();
        }