示例#1
0
        //  Set address to listen on. return the used port
        public virtual void SetAddress(String addr)
        {
            m_address.Resolve(addr, m_options.IPv4Only);

            m_endpoint = m_address.ToString();
            try
            {
                m_handle = AsyncSocket.Create(m_address.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                if (!m_options.IPv4Only && m_address.Address.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    try
                    {
                        // This is not supported on old windows operation system and might throw exception
                        m_handle.SetSocketOption(SocketOptionLevel.IPv6, IPv6Only, 0);
                    }
                    catch
                    {
                    }
                }

                m_handle.ExclusiveAddressUse = false;
                m_handle.Bind(m_address.Address);
                m_handle.Listen(m_options.Backlog);

                m_socket.EventListening(m_endpoint, m_handle);

                m_port = m_handle.LocalEndPoint.Port;
            }
            catch (SocketException ex)
            {
                Close();
                throw NetMQException.Create(ex);
            }
        }
示例#2
0
文件: TcpListener.cs 项目: r618/netmq
        /// <summary>
        /// Set address to listen on.
        /// </summary>
        /// <param name="addr">a string denoting the address to set this to</param>
        public virtual void SetAddress([NotNull] string addr)
        {
            m_address.Resolve(addr, m_options.IPv4Only);

            try
            {
                m_handle = AsyncSocket.Create(m_address.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                Debug.Assert(m_handle != null);

                if (!m_options.IPv4Only && m_address.Address.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    try
                    {
                        // This is not supported on old windows operating systems and might throw exception
                        m_handle.SetSocketOption(SocketOptionLevel.IPv6, IPv6Only, 0);
                    }
                    catch
                    {
                    }
                }

#if NETSTANDARD1_3
                // This command is failing on linux
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    m_handle.ExclusiveAddressUse = false;
                }
#else
                m_handle.ExclusiveAddressUse = false;
#endif
                m_handle.Bind(m_address.Address);
                m_handle.Listen(m_options.Backlog);

                // Copy the port number after binding in case we requested a system-allocated port number (TCP port zero)
                m_address.Address.Port = m_handle.LocalEndPoint.Port;
                m_endpoint             = m_address.ToString();

                m_socket.EventListening(m_endpoint, m_handle);

                m_port = m_handle.LocalEndPoint.Port;
            }
            catch (SocketException ex)
            {
                Close();
                throw NetMQException.Create(ex);
            }
        }
示例#3
0
文件: PgmSender.cs 项目: r618/netmq
        public void Init([NotNull] PgmAddress pgmAddress)
        {
            m_pgmAddress = pgmAddress;

            m_pgmSocket = new PgmSocket(m_options, PgmSocketType.Publisher, (PgmAddress)m_addr.Resolved);
            m_pgmSocket.Init();

            m_socket = m_pgmSocket.Handle;

            var localEndpoint = new IPEndPoint(IPAddress.Any, 0);

            m_socket.Bind(localEndpoint);

            m_pgmSocket.InitOptions();

            m_outBufferSize = m_options.PgmMaxTransportServiceDataUnitLength;
            m_outBuffer     = new ByteArraySegment(new byte[m_outBufferSize]);
        }
示例#4
0
        public void Init([NotNull] PgmAddress pgmAddress)
        {
            m_pgmAddress = pgmAddress;

            m_pgmSocket = new PgmSocket(m_options, PgmSocketType.Publisher, m_addr.Resolved as PgmAddress);
            m_pgmSocket.Init();

            m_socket = m_pgmSocket.Handle;

            var localEndpoint = new IPEndPoint(IPAddress.Any, 0);

            m_socket.Bind(localEndpoint);

            m_pgmSocket.InitOptions();

            m_outBufferSize = Config.PgmMaxTPDU;
            m_outBuffer     = new ByteArraySegment(new byte[m_outBufferSize]);
        }
示例#5
0
        /// <exception cref="InvalidException">Unable to parse the address's port number, or the IP address could not be parsed.</exception>
        /// <exception cref="NetMQException">Error establishing underlying socket.</exception>
        public void Init(string network)
        {
            m_address = new PgmAddress(network);

            m_pgmSocket = new PgmSocket(m_options, PgmSocketType.Listener, m_address);
            m_pgmSocket.Init();

            m_handle = m_pgmSocket.Handle;

            try
            {
                m_handle.Bind(m_address.Address);
                m_pgmSocket.InitOptions();
                m_handle.Listen(m_options.Backlog);
            }
            catch (SocketException ex)
            {
                Close();

                throw NetMQException.Create(ex);
            }

            m_socket.EventListening(m_address.ToString(), m_handle);
        }
示例#6
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();
        }
示例#7
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);
                    }
                }
            }
        }
示例#8
0
文件: Program.cs 项目: sk8tz/AsyncIO
        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();
        }
示例#9
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();
        }