Пример #1
0
 public override void InitPlugin()
 {
     NetSocket.Connect("127.0.0.1", 9007);
     NetSocket.ConnectCompleted        += _mSocket_ConnectCompleted;
     NetSocket.ReceiveMessageCompleted += Socket_ReceiveMessageCompleted;
     NetSocket.OnCatchSocketError      += NetSocket_OnCatchSocketError;
 }
Пример #2
0
        public void TestPipeClients()
        {
            Until((port, done) =>
            {
                var serverA = new AsyncSocket();
                var serverB = new AsyncSocket();

                var socketA = new AsyncSocket();
                var socketB = new AsyncSocket();

                serverA.Listen(port, socket => socket.Read(text =>
                {
                    Assert.AreEqual("Hello", text);
                    socket.Write("world!");
                }));
                socketA.Connect(Host, port);

                serverB.Listen(port + 1, socket =>
                {
                    socket.Read(text =>
                    {
                        Assert.AreEqual("world!", text);
                        done();
                    });
                    socket.Write("Hello");
                });

                socketB.Connect(Host, port + 1, () => { });

                SocketPipe.PipeSockets(socketA, socketB);
            });
        }
Пример #3
0
        public void TestServerToClient()
        {
            Until((port, done) =>
            {
                var portTestServer = port;
                var portServer     = portTestServer + 1;

                var testServer = new AsyncSocket();
                var server     = new AsyncSocket();
                var client     = new AsyncSocket();
                var netro      = new Netro.Netro();

                server.Listen(portServer);
                netro.ServerToClient(server, Host, portTestServer);

                testServer.Listen(portTestServer, socket => socket.Read(text =>
                {
                    Assert.AreEqual("Hello", text);
                    socket.Write("world!");
                }));

                client.Connect(Host, portServer, () =>
                {
                    client.Read(text =>
                    {
                        Assert.AreEqual("world!", text);
                        done();
                    });
                    client.Write("Hello");
                });
            });
        }
Пример #4
0
        public void TestPipeServerClient()
        {
            Until((port, done) =>
            {
                var server = new AsyncSocket();

                var socketA = new AsyncSocket();
                var socketB = new AsyncSocket();
                var portA   = port;
                var portB   = portA + 1;

                server.Listen(portA, socket => socket.Read(text =>
                {
                    Assert.AreEqual("Hello", text);
                    socket.Write("world!");
                }));

                socketB.Listen(portB, socket =>
                {
                    var c = new AsyncSocket();
                    c.Connect(Host, portB, () => SocketPipe.PipeSockets(socket, c));
                });

                socketA.Read(text =>
                {
                    Assert.AreEqual("world!", text);
                    done();
                });
                socketA.Connect(Host, portA, () => socketA.Write("Hello"));
            });
        }
Пример #5
0
        /// <summary>
        /// Internal function to start the actual connection establishment.
        /// </summary>
        private void StartConnecting()
        {
            Debug.Assert(m_s == null);

            // Create the socket.
            try
            {
                m_s = AsyncSocket.Create(m_addr.Resolved.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            }
            catch (SocketException)
            {
                AddReconnectTimer();
                return;
            }

            m_ioObject.AddSocket(m_s);
            m_handleValid = true;

            // Connect to the remote peer.
            try
            {
                m_s.Connect(m_addr.Resolved.Address.Address, m_addr.Resolved.Address.Port);
                m_socket.EventConnectDelayed(m_endpoint, ErrorCode.InProgress);
            }
            catch (SocketException ex)
            {
                OutCompleted(ex.SocketErrorCode, 0);
            }
            // TerminatingException can occur in above call to EventConnectDelayed via
            // MonitorEvent.Write if corresponding PairSocket has been sent Term command
            catch (TerminatingException)
            {}
        }
Пример #6
0
        public void TestPreconnect()
        {
            Until((port, done) =>
            {
                var count   = 0;
                var clients = 0;
                var server  = new AsyncSocket();
                server.Listen(port);
                server.Preconnect(() =>
                {
                    count++;
                    return(count % 2 == 0);
                });
                server.Connect(socket =>
                {
                    clients++;
                    if (count < 10)
                    {
                        return;
                    }
                    Assert.AreEqual(10, count);
                    Assert.AreEqual(5, clients);
                    done();
                });

                for (var i = 0; i < 10; i++)
                {
                    var client = new AsyncSocket();
                    client.Connect(Host, port);
                }
            });
        }
Пример #7
0
        private void fetchButton_Click(object sender, EventArgs e)
        {
            fetchButton.Enabled = false;
            sslCheckBox.Enabled = false;

            logRichTextBox.Clear();

            if (sslCheckBox.Checked)
            {
                asyncSocket.Connect(FETCH_HOST, 443);
            }
            else
            {
                asyncSocket.Connect(FETCH_HOST, 80);
            }
        }
Пример #8
0
        /// <summary>
        /// Connect with manually entered info
        /// </summary>
        public void Connect()
        {
            if (socket != null)
            {
                socket.Close();
                socket = null;
            }

            Connected            = false;
            ConnectionFailed     = false;
            Authenticated        = false;
            AuthenticationFailed = false;

            Log.Info("Setting up WifiRemote connection to {0}:{1}", Address, Port);

            socket             = new AsyncSocket();
            socket.DidConnect += new AsyncSocket.SocketDidConnect(socket_DidConnect);
            socket.DidRead    += new AsyncSocket.SocketDidRead(socket_DidRead);
            socket.AllowMultithreadedCallbacks = true;
            if (!socket.Connect(Address, 8017))
            {
                Log.Warn("WifiRemoteClient: Could not connect to server, AsyncSocket connect failed");
                ConnectionFailed = true;
            }
        }
Пример #9
0
        //  Internal function to start the actual connection establishment.
        private void StartConnecting()
        {
            Debug.Assert(m_s == null);

            //  Create the socket.
            try
            {
                m_s = AsyncSocket.Create(m_addr.Resolved.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            }
            catch (SocketException)
            {
                AddReconnectTimer();
                return;
            }

            m_ioObject.AddSocket(m_s);
            m_handleValid = true;

            //  Connect to the remote peer.
            try
            {
                m_s.Connect(m_addr.Resolved.Address.Address, m_addr.Resolved.Address.Port);
                m_socket.EventConnectDelayed(m_endpoint, ErrorCode.InProgres);
            }
            catch (SocketException ex)
            {
                OutCompleted(ex.SocketErrorCode, 0);
            }
        }
Пример #10
0
        /// <summary>
        /// Connect with manually entered info
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonConnect_Click(object sender, EventArgs e)
        {
            if (socket != null)
            {
                socket.Close();
                socket = null;
            }

            Log("Connecting ...", null, "Connecting to server");

            socket              = new AsyncSocket();
            socket.WillConnect += new AsyncSocket.SocketWillConnect(socket_WillConnect);
            socket.DidConnect  += new AsyncSocket.SocketDidConnect(socket_DidConnect);
            socket.WillClose   += new AsyncSocket.SocketWillClose(socket_WillClose);
            socket.DidClose    += new AsyncSocket.SocketDidClose(socket_DidClose);
            socket.DidRead     += new AsyncSocket.SocketDidRead(socket_DidRead);
            socket.DidWrite    += new AsyncSocket.SocketDidWrite(socket_DidWrite);


            ushort thePort;
            bool   isValidPort = ushort.TryParse(textBoxPort.Text, out thePort);

            if (!isValidPort || !socket.Connect(textBoxAddress.Text, thePort))
            {
                Log(null, "Could not connect to server: AsyncSocket connect failed", "Could not connect to server");
                MessageBox.Show("Could not connect to server", "Error");
            }
        }
Пример #11
0
        /// <summary>
        /// Connect to server selected in autodetect list
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonConnectDetected_Click(object sender, EventArgs e)
        {
            if (servers.Count <= 0 || listBoxServers.SelectedItem == null)
            {
                return;
            }

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

            Log("Connecting ...", null, "Connecting to server");

            socket              = new AsyncSocket();
            socket.WillConnect += new AsyncSocket.SocketWillConnect(socket_WillConnect);
            socket.DidConnect  += new AsyncSocket.SocketDidConnect(socket_DidConnect);
            socket.WillClose   += new AsyncSocket.SocketWillClose(socket_WillClose);
            socket.DidClose    += new AsyncSocket.SocketDidClose(socket_DidClose);
            socket.DidRead     += new AsyncSocket.SocketDidRead(socket_DidRead);
            socket.DidWrite    += new AsyncSocket.SocketDidWrite(socket_DidWrite);

            if (!socket.Connect(((NetService)listBoxServers.SelectedItem).HostName, (ushort)((NetService)listBoxServers.SelectedItem).Port))
            {
                Log(null, "Could not connect to server: AsyncSocket connect failed", "Could not connect to server");
                MessageBox.Show("Could not connect to server", "Error");
            }
        }
Пример #12
0
 /// <summary>
 /// Connect
 /// </summary>
 public void Connect()
 {
     try {
         Socket.Connect(Model.Server, Model.Port);
     } catch (Exception ex) {
         if (ProcessError != null)
         {
             ProcessError(ex, "Connect");
         }
     }
 }
Пример #13
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();
                }
            }
        }
Пример #14
0
        private void StartConnecting()
        {
            m_state = State.Connecting;

            try
            {
                m_socket.Connect(m_pgmAddress.Address);
            }
            catch (SocketException ex) // when (ex.SocketErrorCode == SocketError.InvalidArgument)
            {
                Error();
            }
        }
Пример #15
0
        public void TestServerDisconnect()
        {
            Until((port, done) =>
            {
                var server = new AsyncSocket();
                server.Listen(port, socket => socket.Disconnect());

                var client = new AsyncSocket();
                client.Disconnect(done);
                client.Connect(Host, port);
                client.Read(text => {});
            });
        }
Пример #16
0
 private void cmdConnect_Click(object sender, EventArgs e)
 {
     if (cmdConnect.Text == "Connect")
     {
         _socket.Connect(txtServer.Text, long.Parse(txtPort.Text));
     }
     else
     {
         _socket.Send("close" + Environment.NewLine);
         System.Threading.Thread.Sleep(200);
         _socket.Close();
     }
 }
Пример #17
0
        public void TestPing()
        {
            Until((port, done) =>
            {
                var server = new AsyncSocket();
                server.Listen(port, socket => socket.Read(text =>
                {
                    Assert.AreEqual("Hello, world!", text);
                    done();
                }));

                var client = new AsyncSocket();
                client.Connect(Host, port, () => client.Write("Hello, world!"));
            });
        }
Пример #18
0
        public void thread_fun()
        {
            ++active_thread_count;

            m_clientSocket.Connect("127.0.0.1", 56665);
            ++wait_connect_count;
            if (!m_clientItem.Handle.WaitOne(1000))
            {
                ++connect_falied;
                --wait_connect_count;
                --active_thread_count;
                m_clientItem.Active = false;
                return;
            }
            --wait_connect_count;


            Console.WriteLine(m_name + "connected to server");

            for (int i = 0; i < 5; ++i)
            {
                var buffter = Encoding.UTF8.GetBytes("thread message:" + m_name);
                try
                {
                    m_clientSocket.Send(buffter);
                    ++waiting_send_count;
                    Console.WriteLine($"to send data:{m_name}");
                    if (!m_clientItem.Handle.WaitOne(5000)) // wait for data to be send: 500ms
                    {
                        ++send_failed;
                        break;
                    }
                    --waiting_send_count;
                    Console.WriteLine($"send data:{m_name}");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
                //m_clientItem.Handle.WaitOne(); // wait for data to be send
                Console.WriteLine(m_name + "data sended.");

                Thread.Sleep(1000);
            }

            Console.WriteLine("client loop ended");
            --active_thread_count;
        }
Пример #19
0
        public void TestServerPongReadAfterConnect()
        {
            Until((port, done) =>
            {
                var server = new AsyncSocket();
                server.Listen(port, socket => socket.Write("Hello"));

                var client = new AsyncSocket();
                client.Connect(Host, port);
                client.Read(text =>
                {
                    Assert.AreEqual("Hello", text);
                    done();
                });
            });
        }
Пример #20
0
        public void FullTest()
        {
            Until((port, done) =>
            {
                var serverPortA = port + 1;
                var serverPortB = port + 2;

                var serverA = new AsyncSocket();
                var serverB = new AsyncSocket();
                var clientA = new AsyncSocket();

                var reverseServer = new ReverseAsyncSocket();
                var reverseClient = new ReverseAsyncSocket();

                var netro = new Netro.Netro();

                serverA.Listen(serverPortA);
                serverB.Listen(serverPortB);
                reverseServer.Listen(port);

                netro.ReverseServerToServer(reverseServer, serverA);
                netro.ReverseClientToClient(reverseClient, Host, serverPortB);

                reverseServer.Connect(s =>
                {
                    serverB.Connect(socket => socket.Read(text =>
                    {
                        Assert.AreEqual("Hello", text);
                        socket.Write("world!");
                    }));

                    clientA.Connect(Host, serverPortA, () =>
                    {
                        clientA.Write("Hello");
                        clientA.Read(text =>
                        {
                            Assert.AreEqual("world!", text);
                            done();
                        });
                    });
                });

                reverseClient.Connect(Host, port, () => { });
            });
        }
Пример #21
0
        public void Plug(IOThread ioThread, SessionBase session)
        {
            m_encoder.SetMsgSource(session);

            // get the first message from the session because we don't want to send identities
            var msg = new Msg();

            msg.InitEmpty();

            bool ok = session.PullMsg(ref msg);

            if (ok)
            {
                msg.Close();
            }

            AddSocket(m_socket);

            m_state = State.Connecting;
            m_socket.Connect(m_pgmAddress.Address);
        }
Пример #22
0
        public void TestReverseServerToServer()
        {
            Until((port, done) =>
            {
                var reverseServer = new ReverseAsyncSocket();
                var server        = new AsyncSocket();

                var reverseClient = new ReverseAsyncSocket();
                var client        = new AsyncSocket();

                var netro      = new Netro.Netro();
                var serverPort = port + 1;

                reverseServer.Listen(port);
                server.Listen(serverPort);

                netro.ReverseServerToServer(reverseServer, server);

                reverseClient.ReadString((tid, command, text) =>
                {
                    Assert.AreEqual("Hello", text);
                    reverseClient.Write(tid, "world!");
                });
                client.Read(text =>
                {
                    Assert.AreEqual("world!", text);
                    done();
                });

                reverseClient.Connect(Host, port,
                                      () =>
                {
                    client.Connect(Host, serverPort, () =>
                    {
                        client.Write("Hello");
                    });
                });
            });
        }
Пример #23
0
        public void TestMassiveDisconnect()
        {
            Until((port, done) =>
            {
                const int clientCount = 100;
                var count             = 0;

                var server = new AsyncSocket();
                server.Listen(port, socket =>
                {
                    count++;
                    socket.Disconnect(() => count--);
                    socket.Read(text => { });
                });

                var clients = Enumerable.Range(0, clientCount).Select(i =>
                {
                    var client = new AsyncSocket();
                    client.Connect(Host, port);
                    return(client);
                }).ToList();

                while (count < clientCount)
                {
                    Thread.Sleep(100);
                }

                Assert.AreEqual(clientCount, count);

                clients.ForEach(client => client.Disconnect());
                while (count > 0)
                {
                    Thread.Sleep(100);
                }

                Assert.AreEqual(0, count);
                done();
            });
        }
Пример #24
0
        public void TestServerToClientDisconnect()
        {
            Until((port, done) =>
            {
                var portTestServer = port;
                var portServer     = portTestServer + 1;

                var testServer = new AsyncSocket();
                var server     = new AsyncSocket();
                var client     = new AsyncSocket();
                var netro      = new Netro.Netro();

                server.Listen(portServer);
                netro.ServerToClient(server, Host, portTestServer);

                testServer.Listen(portTestServer, socket => socket.Disconnect());

                client.Connect(Host, portServer, () =>
                {
                    client.Read(text => { });
                    client.Disconnect(done);
                });
            });
        }
Пример #25
0
        public void ReverseClientToClient()
        {
            Until((port, done) =>
            {
                var serverPort = port + 1;

                var reverseServer = new ReverseAsyncSocket();
                var server        = new AsyncSocket();

                var reverseClient = new ReverseAsyncSocket();
                var netro         = new Netro.Netro();

                netro.ReverseClientToClient(reverseClient, Host, serverPort);

                reverseServer.Listen(port);
                server.Listen(serverPort);

                reverseClient.Connect(Host, port, () => { });

                server.Connect(socket => socket.Read(text =>
                {
                    Assert.AreEqual("Hello", text);
                    socket.Write("world!");
                }));

                reverseServer.Connect(socket =>
                {
                    socket.ReadString((id, command, text) =>
                    {
                        Assert.AreEqual("world!", text);
                        done();
                    });
                    socket.Write(42, "Hello");
                });
            });
        }
Пример #26
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();
        }
Пример #27
0
        public bool Connect(int timeout = 5000)
        {
            if (!isConnected)
            {
                lock (clientLock)
                {
                    setInstallationDirectory();
                    if (string.IsNullOrEmpty(enginePath))
                    {
                        return(false);
                    }

                    if (Process.GetProcessesByName(Path.GetFileNameWithoutExtension(enginePath)).Length == 0)
                    {
                        try
                        {
                            using (Process p = Process.Start(enginePath)) { }
                        }
                        catch (Exception ex)
                        {
                            log("Failed to start '{0}' - {1}", enginePath, ex.Message);
                            return(false);
                        }
                    }
                    else
                    {
                        log("AceStream already running");
                    }

                    string portFile = Path.Combine(installDir, "acestream.port");
                    int    tries    = timeout / 100;
                    while (!File.Exists(portFile))
                    {
                        tries--;
                        if (tries < 0)
                        {
                            return(false);
                        }
                        Thread.Sleep(100);
                    }

                    try
                    {
                        port = int.Parse(File.ReadAllText(portFile));
                        log("Using port {0}", port);
                    }
                    catch (Exception ex)
                    {
                        log("Failed to get port from '{0}' - {1}", portFile, ex.Message);
                        log("Using default port {0}", DEFAULT_PORT);
                        port = DEFAULT_PORT; //try default port
                    }

                    if (!socket.Connect(host, (ushort)port))
                    {
                        socket.Close();
                        log("Error connecting to {0}:{1)", host, port);
                        return(false);
                    }
                    isConnected = true;
                }
            }
            return(true);
        }
Пример #28
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();
        }
Пример #29
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();
        }