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")); }); }
// 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); } }
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); }); }
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"); }); }); }
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); } }); }
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 => {}); }); }
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!")); }); }
/// <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); } }
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(); }); }); }
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, () => { }); }); }
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(); }); }
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"); }); }); }); }
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); }); }); }
/// <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); }
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"); }); }); }
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(); }
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(); }
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(); }
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); } } } }