Пример #1
0
        public void BasicRoundTrip()
        {
            var serializer = new JsonCommonSerializer();

            var port = new Random().Next(6000, 60000);

            var listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram);

            listener.Bind(IPAddress.Loopback, port);
            listener.Listen(100);
            var serverTransport = listener.GenerateTransportSource(true);
            var serverRouter    = new DefaultMessageRouter(serverTransport, serializer);

            serverRouter.AddService <IMyService>(new MyService());

            var client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram);

            client.Connect(IPAddress.Loopback, port);
            var clientTransport = client.GenerateTransportSource(false);
            var clientRouter    = new DefaultMessageRouter(clientTransport, serializer);
            var proxy           = clientRouter.AddInterface <IMyService>();

            var result = proxy.Add(3, 4).Result;

            Assert.Equal(7, result);

            clientRouter.Dispose();
            clientTransport.Dispose();
            client.Dispose();

            serverRouter.Dispose();
            serverTransport.Dispose();
            listener.Dispose();
        }
Пример #2
0
        public void Wait_for_accept()
        {
            using (Udt.SocketPoller poller = new Udt.SocketPoller())
                using (Udt.Socket socket = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream))
                {
                    socket.Bind(IPAddress.Loopback, 0);
                    socket.Listen(100);
                    ManualResetEvent doneEvent = new ManualResetEvent(false);

                    poller.AddSocket(socket);

                    Task.Factory.StartNew(() =>
                    {
                        using (Udt.Socket client = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream))
                        {
                            client.Connect(IPAddress.Loopback, socket.LocalEndPoint.Port);
                            doneEvent.WaitOne(1000);
                        }
                    });

                    Assert.IsTrue(poller.Wait(TimeSpan.FromSeconds(1)));
                    CollectionAssert.AreEqual(new[] { socket }, poller.WriteSockets);
                    CollectionAssert.AreEqual(new[] { socket }, poller.ReadSockets);

                    Udt.Socket acceptedSocket = socket.Accept();
                    acceptedSocket.Dispose();
                    doneEvent.Set();

                    Assert.IsTrue(poller.Wait(TimeSpan.Zero));
                    CollectionAssert.AreEqual(new[] { socket }, poller.WriteSockets);
                    CollectionAssert.IsEmpty(poller.ReadSockets);
                }
        }
Пример #3
0
        public void Accept()
        {
            ManualResetEvent acceptedEvent = new ManualResetEvent(false);

            int port = _portNum++;

            var serverTask = Task.Factory.StartNew(() =>
            {
                using (Udt.Socket server = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream))
                {
                    server.Bind(IPAddress.Loopback, port);
                    server.Listen(1);

                    using (Udt.Socket accept = server.Accept())
                    {
                        acceptedEvent.Set();
                    }
                }
            });

            using (Udt.Socket client = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream))
            {
                client.Connect(IPAddress.Loopback, port);
                acceptedEvent.WaitOne();
            }

            serverTask.Wait();
        }
Пример #4
0
		public void BasicRoundTrip()
		{
			var serializer = new JsonCommonSerializer();

			var port = new Random().Next(6000, 60000);

			var listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram);
			listener.Bind(IPAddress.Loopback, port);
			listener.Listen(100);
			var serverTransport = listener.GenerateTransportSource(true);
			var serverRouter = new DefaultMessageRouter(serverTransport, serializer);
			serverRouter.AddService<IMyService>(new MyService());

			var client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram);
			client.Connect(IPAddress.Loopback, port);
			var clientTransport = client.GenerateTransportSource(false);
			var clientRouter = new DefaultMessageRouter(clientTransport, serializer);
			var proxy = clientRouter.AddInterface<IMyService>();

			var result = proxy.Add(3, 4).Result;
			Assert.Equal(7, result);

			clientRouter.Dispose();
			clientTransport.Dispose();
			client.Dispose();

			serverRouter.Dispose();
			serverTransport.Dispose();
			listener.Dispose();
		}
Пример #5
0
        public void Accept()
        {
            ManualResetEvent acceptedEvent = new ManualResetEvent(false);

            int port = _portNum++;

            var serverTask = Task.Factory.StartNew(() =>
            {
                using (Udt.Socket server = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream))
                {
                    server.Bind(IPAddress.Loopback, port);
                    server.Listen(1);

                    using (Udt.Socket accept = server.Accept())
                    {
                        acceptedEvent.Set();
                    }
                }
            });

            using (Udt.Socket client = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream))
            {
                client.Connect(IPAddress.Loopback, port);
                acceptedEvent.WaitOne();
            }

            serverTask.Wait();
        }
Пример #6
0
        void doRendezvous(MessageResponseDelegate response)
        {
            response?.Invoke("Attempting to initiate rendezvous connection.");

            response?.Invoke("Binding to random socket.");
            System.Net.Sockets.Socket udp = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
            udp.Bind(new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0));

            response?.Invoke("Successfully bound to UDP endpoint " + udp.LocalEndPoint.ToString());

            response?.Invoke("Sending UDP punch.");
            byte[] b = App.serializer.serialize(new Commands.BeginPunchCommand()
            {
                myId = App.theCore.id, port = (ushort)((System.Net.IPEndPoint)udp.LocalEndPoint).Port
            });
            App.udpSend(b, actualEndpoint);

            response?.Invoke("Waiting for UDP response.");
            rendezvousSemaphore.WaitOne();

            response?.Invoke("Received a UDP response! Remote endpoint is " + rendezvousAddress.ToString());


            response?.Invoke("Binding UDT to UDP socket.");
            Udt.Socket s = new Udt.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream);

            s.ReuseAddress = true;
            s.Bind(udp);

            s.Rendezvous = true;

            response?.Invoke("Performing UDT control rendezvous...");
            try
            {
                s.Connect(rendezvousAddress);
            }
            catch
            {
                return;
            }

            while (s.State == Udt.SocketState.Connecting)
            {
                System.Threading.Thread.Sleep(10);
            }
            controlConnection = new UdtOutgoingConnection(s, udp);
            dataConnection    = controlConnection;

            response?.Invoke("Rendezvous connection successful!");
            controlConnection.send(new Model.Commands.GetFileListing("/"));

            dataConnection.commandReceived    += commandReceived;
            controlConnection.commandReceived += commandReceived;
        }
Пример #7
0
        public void endPunch(System.Net.IPEndPoint sender)
        {
            SystemLog.addEntry("Received BeginPunch from " + sender.ToString());
            System.Net.Sockets.Socket udp = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);

            udp.Bind(new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0));
            SystemLog.addEntry("Bound " + udp.LocalEndPoint.ToString());

            byte[] b = App.serializer.serialize(new Commands.EndPunchCommand()
            {
                myId = App.theCore.id, port = (ushort)((System.Net.IPEndPoint)udp.LocalEndPoint).Port
            });
            if (isLocal)
            {
                foreach (System.Net.IPAddress a in internalAddress)
                {
                    SystemLog.addEntry("Sent EndPunch to " + new System.Net.IPEndPoint(a, localControlPort));
                    App.udpSend(b, new System.Net.IPEndPoint(a, localControlPort));
                }
            }
            else
            {
                SystemLog.addEntry("Sent EndPunch to " + actualEndpoint);
                App.udpSend(b, actualEndpoint);
            }
            System.Threading.Thread t = new System.Threading.Thread(delegate()
            {
                try
                {
                    Udt.Socket s   = new Udt.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream);
                    s.ReuseAddress = true;

                    s.Bind(udp);
                    s.Rendezvous = true;
                    SystemLog.addEntry("Beginning rendezvous...");
                    s.Connect(sender);
                    while (s.State == Udt.SocketState.Connecting)
                    {
                        System.Threading.Thread.Sleep(10);
                    }
                    App.theCore.addIncomingConnection(new UdtIncomingConnection(s, udp));

                    SystemLog.addEntry("Rendezvous successful!");
                }
                catch (Exception e)
                {
                    SystemLog.addEntry("Error rendezvous'ing to " + sender.ToString() + " - " + e.Message);
                }
            });
            t.Name         = "Rendezvous thread";
            t.IsBackground = true;
            t.Start();
        }
Пример #8
0
        static Udt.Socket PeerConnect(Socket socket, string remoteAddr, int remotePort)
        {
            bool bConnected = false;
            int  retry      = 0;

            Udt.Socket client = null;

            while (!bConnected)
            {
                try
                {
                    DateTime now = InternetTime.Get();

                    int sleepTimeToSync = SleepTime(now);

                    Console.WriteLine("[{0}] - Waiting {1} sec to sync with other peer",
                                      now.ToLongTimeString(),
                                      sleepTimeToSync);
                    System.Threading.Thread.Sleep(sleepTimeToSync * 1000);

                    GetExternalEndPoint(socket);

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

                    client = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream);

                    client.SetSocketOption(Udt.SocketOptionName.Rendezvous, true);

                    client.Bind(socket);

                    Console.Write("\r{0} - Trying to connect to {1}:{2}.  ",
                                  retry++, remoteAddr, remotePort);

                    client.Connect(remoteAddr, remotePort);

                    Console.WriteLine("Connected successfully to {0}:{1}",
                                      remoteAddr, remotePort);

                    bConnected = true;
                }
                catch (Exception e)
                {
                    Console.Write(e.Message.Replace(Environment.NewLine, ". "));
                }
            }

            return(client);
        }
Пример #9
0
        static int Main(string[] args)
        {
            if ((args.Length != 4) || (0 == int.Parse(args[1])))
            {
                Console.WriteLine("Usage: ReceiveFile server_ip server_port remote_filename local_filename");
                return(1);
            }

            try
            {
                using (Udt.Socket client = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream))
                {
                    client.Connect(IPAddress.Parse(args[0]), int.Parse(args[1]));

                    // Send name information of the requested file
                    string name      = args[2];
                    byte[] nameBytes = Encoding.UTF8.GetBytes(name);

                    client.Send(BitConverter.GetBytes(nameBytes.Length), 0, sizeof(int));
                    client.Send(nameBytes);

                    // Get size information
                    long   size;
                    byte[] file = new byte[1024];

                    client.Receive(file, 0, sizeof(long));
                    size = BitConverter.ToInt64(file, 0);

                    // Receive the file
                    string localName = args[3];
                    client.ReceiveFile(localName, size);

                    client.Close();
                }

                Console.ReadKey(true);
                return(0);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("Error receiving file: {0}", ex.Message);
                Console.ReadKey(true);
                return(2);
            }
        }
Пример #10
0
        public override void Connect(System.Net.IPEndPoint endpoint)
        {
            if (udtSocket.State != Udt.SocketState.Open &&
                udtSocket.State != Udt.SocketState.Initial)
            {
                throw new Exception("UDT socket not ready to connect.");
            }

            //Connect this layer to the desired endpoint. UDT should handle this for us.
            udtSocket.Connect(endpoint);

            if (udtSocket.State != Udt.SocketState.Connected)
            {
                throw new Exception("UDT connect failed.");
            }

            //Wrap a new stream around the newly connected socket.
            networkStream = new Udt.NetworkStream(udtSocket);
        }
Пример #11
0
        public void ReceiveFile_stream()
        {
            ManualResetEvent serverDoneEvent = new ManualResetEvent(false);
            ManualResetEvent clientDoneEvent = new ManualResetEvent(false);
            int    port        = _portNum++;
            string path        = GetFile("The quick brown fox jumped over the lazy dog");
            string receivePath = GetFile();

            var serverTask = Task.Factory.StartNew(() =>
            {
                using (Udt.Socket server = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream))
                {
                    server.Bind(IPAddress.Loopback, port);
                    server.Listen(1);

                    using (Udt.Socket accept = server.Accept())
                        using (Udt.StdFileStream file = new Udt.StdFileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            accept.SendFile(file);

                            serverDoneEvent.Set();
                            Assert.IsTrue(clientDoneEvent.WaitOne(1000));
                        }
                }
            });

            using (Udt.Socket client = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream))
                using (Udt.StdFileStream file = new Udt.StdFileStream(receivePath, FileMode.Open, FileAccess.ReadWrite))
                {
                    client.Connect(IPAddress.Loopback, port);
                    Assert.AreEqual(44, client.ReceiveFile(file, 44));

                    file.Close();

                    CollectionAssert.AreEqual(File.ReadAllBytes(path), File.ReadAllBytes(receivePath));

                    clientDoneEvent.Set();
                    Assert.IsTrue(serverDoneEvent.WaitOne(1000));
                }

            serverTask.Wait();
        }
Пример #12
0
        public void Send_receive()
        {
            ManualResetEvent serverDoneEvent = new ManualResetEvent(false);
            ManualResetEvent clientDoneEvent = new ManualResetEvent(false);
            int port = _portNum++;

            var serverTask = Task.Factory.StartNew(() =>
            {
                using (Udt.Socket server = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream))
                {
                    server.Bind(IPAddress.Loopback, port);
                    server.Listen(1);

                    using (Udt.Socket accept = server.Accept())
                    {
                        accept.Send(new byte[] { 1, 2, 3 });

                        byte[] buffer = new byte[1024];
                        Assert.AreEqual(3, accept.Receive(buffer));

                        serverDoneEvent.Set();
                        Assert.IsTrue(clientDoneEvent.WaitOne(1000));
                    }
                }
            });

            using (Udt.Socket client = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream))
            {
                client.Connect(IPAddress.Loopback, port);

                byte[] buffer = new byte[1024];
                Assert.AreEqual(3, client.Receive(buffer));
                CollectionAssert.AreEqual(new byte[] { 1, 2, 3 }, buffer.Take(3));

                client.Send(new byte[] { 1, 2, 3 });

                clientDoneEvent.Set();
                Assert.IsTrue(serverDoneEvent.WaitOne(1000));
            }

            serverTask.Wait();
        }
Пример #13
0
        public void Get_State()
        {
            ManualResetEvent serverDoneEvent = new ManualResetEvent(false);
            ManualResetEvent clientDoneEvent = new ManualResetEvent(false);
            int port = _portNum++;

            var serverTask = Task.Factory.StartNew(() => {
                using (Udt.Socket server = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream)) {
                    server.Bind(IPAddress.Loopback, port);
                    Assert.AreEqual(Udt.SocketState.Open, server.State);
                    server.Listen(1);
                    Assert.AreEqual(Udt.SocketState.Listening, server.State);

                    using (Udt.Socket accept = server.Accept()) {
                        Assert.AreEqual(Udt.SocketState.Open, server.State);
                        serverDoneEvent.Set();
                        Assert.IsTrue(clientDoneEvent.WaitOne(1000));
                    }
                }
            });

            using (Udt.Socket socket = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream))
            {
                Assert.AreEqual(Udt.SocketState.Initial, socket.State);
                Assert.AreEqual(Udt.SocketState.Initial, socket.GetSocketOption(Udt.SocketOptionName.State));
                AssertReadOnly(socket, Udt.SocketOptionName.State);

                socket.Connect(IPAddress.Loopback, port);
                Assert.AreEqual(Udt.SocketState.Connected, socket.State);

                serverDoneEvent.WaitOne(1000);
                clientDoneEvent.Set();

                socket.Close();
                Assert.AreEqual(Udt.SocketState.Closed, socket.State);
                Assert.AreEqual(Udt.SocketState.Closed, socket.GetSocketOption(Udt.SocketOptionName.State));
            }
        }
Пример #14
0
        internal static void SendFiles(NetIncomingMessage msg)
        {
            Messages message = Messages.FromByteArray(msg.Data);
            Guid id = new Guid((string)message.Data);

            //Messages outGoingMessage = new Messages();
            //outGoingMessage.MessageType = Message.RecieveFile;
            //NetOutgoingMessage outgoingMessage2 = server.CreateMessage();
            //outgoingMessage2.Write(outGoingMessage.ToByteArray());
            //server.SendUnconnectedMessage(outgoingMessage2, msg.SenderEndPoint);

            Udt.Socket socket = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream);
            Udt.StdFileStream fs = new Udt.StdFileStream(userFileList.GetFilePathFromGuid(id), FileMode.Open);
            {
                socket.BlockingSend = true;
                socket.Connect(msg.SenderEndPoint.Address, 10000);
                // Send the file length, in bytes
                socket.Send(BitConverter.GetBytes(fs.Length), 0, sizeof(long));
                // Send the file contents
                socket.SendFile(fs);

            }
        }
Пример #15
0
        public void SendFile_stream()
        {
            ManualResetEvent serverDoneEvent = new ManualResetEvent(false);
            ManualResetEvent clientDoneEvent = new ManualResetEvent(false);
            int port = _portNum++;
            string path = GetFile("The quick brown fox jumped over the lazy dog");

            var serverTask = Task.Factory.StartNew(() =>
            {
                using (Udt.Socket server = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream))
                {
                    server.Bind(IPAddress.Loopback, port);
                    server.Listen(1);

                    using (Udt.Socket accept = server.Accept())
                    using (Udt.StdFileStream file = new Udt.StdFileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        accept.SendFile(file);

                        serverDoneEvent.Set();
                        Assert.IsTrue(clientDoneEvent.WaitOne(1000));
                    }
                }
            });

            using (Udt.Socket client = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream))
            {
                byte[] buffer = new byte[1024];

                client.Connect(IPAddress.Loopback, port);
                Assert.AreEqual(44, client.Receive(buffer));

                CollectionAssert.AreEqual(File.ReadAllBytes(path), buffer.Take(44));

                clientDoneEvent.Set();
                Assert.IsTrue(serverDoneEvent.WaitOne(1000));
            }

            serverTask.Wait();
        }
Пример #16
0
        public void Send_receive()
        {
            ManualResetEvent serverDoneEvent = new ManualResetEvent(false);
            ManualResetEvent clientDoneEvent = new ManualResetEvent(false);
            int port = _portNum++;

            var serverTask = Task.Factory.StartNew(() =>
            {
                using (Udt.Socket server = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream))
                {
                    server.Bind(IPAddress.Loopback, port);
                    server.Listen(1);

                    using (Udt.Socket accept = server.Accept())
                    {
                        accept.Send(new byte[] { 1, 2, 3 });

                        byte[] buffer = new byte[1024];
                        Assert.AreEqual(3, accept.Receive(buffer));

                        serverDoneEvent.Set();
                        Assert.IsTrue(clientDoneEvent.WaitOne(1000));
                    }
                }
            });

            using (Udt.Socket client = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream))
            {
                client.Connect(IPAddress.Loopback, port);

                byte[] buffer = new byte[1024];
                Assert.AreEqual(3, client.Receive(buffer));
                CollectionAssert.AreEqual(new byte[] { 1, 2, 3 }, buffer.Take(3));

                client.Send(new byte[] { 1, 2, 3 });

                clientDoneEvent.Set();
                Assert.IsTrue(serverDoneEvent.WaitOne(1000));
            }

            serverTask.Wait();
        }
Пример #17
0
        public void Benchmark()
        {
            //var serializerSource = new Newtonsoft.Json.JsonSerializer();
            var serializer = new ProtobufCommonSerializer();            //new JsonCommonSerializer(serializerSource); //

            var port = new Random().Next(6000, 60000);

            var listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram);

            listener.Bind(IPAddress.Loopback, port);
            listener.Listen(100);
            var serverTransport = listener.GenerateTransportSource(true);
            var serverRouter    = new DefaultMessageRouter(serverTransport, serializer);

            serverRouter.AddService <ISumService>(new SumService());

            var client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram);

            client.Connect(IPAddress.Loopback, port);
            var clientTransport = client.GenerateTransportSource(false);
            var clientRouter    = new DefaultMessageRouter(clientTransport, serializer);
            var proxy           = clientRouter.AddInterface <ISumService>();

            const int randCnt = 100;
            var       rand    = new Random(42);
            var       randoms = new int[randCnt];

            for (int i = 0; i < randCnt; i++)
            {
                randoms[i] = rand.Next(10000000, 20000000);
            }

            var       sw = new Stopwatch();
            long      timeFromClient = 0, timeToClient = 0;
            const int cnt = 1000;

            for (int j = 0; j < cnt; j++)
            {
                sw.Start();
                var sum = proxy.Sum(randoms).Result;
                sw.Stop();
                Assert.Equal(randoms.Sum(), sum);
                for (int i = 0; i < randCnt; i++)
                {
                    randoms[i] = rand.Next(10000000, 20000000);
                }
                var times = proxy.TimeDiff(Stopwatch.GetTimestamp()).Result;
                timeFromClient += times.Item1;
                timeToClient   += Stopwatch.GetTimestamp() - times.Item2;
            }

            _testOutputHelper.WriteLine("Completed {0} sum passes in {1}ms", cnt, sw.ElapsedMilliseconds);
            _testOutputHelper.WriteLine("Client to server latency: {0}us", timeFromClient / cnt / 10);
            _testOutputHelper.WriteLine("Server to client latency: {0}us", timeToClient / cnt / 10);

            sw.Reset();
            var tree = new SumServiceTree();

            SumServiceTree.FillTree(tree, rand, 2);
            _testOutputHelper.WriteLine("Starting large message transfer.");
            sw.Start();
            var result = proxy.Increment(tree).Result;

            sw.Stop();
            Assert.Equal(tree.Leaf + 1, result.Leaf);
            _testOutputHelper.WriteLine("Completed large transfer in {0}ms", sw.Elapsed.TotalMilliseconds);

            clientRouter.Dispose();
            clientTransport.Dispose();
            client.Dispose();

            serverRouter.Dispose();
            serverTransport.Dispose();
            listener.Dispose();
        }
Пример #18
0
        public void Get_State()
        {
            ManualResetEvent serverDoneEvent = new ManualResetEvent(false);
              ManualResetEvent clientDoneEvent = new ManualResetEvent(false);
              int port = _portNum++;

              var serverTask = Task.Factory.StartNew(() => {
            using (Udt.Socket server = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream)) {
              server.Bind(IPAddress.Loopback, port);
              Assert.AreEqual(Udt.SocketState.Open, server.State);
              server.Listen(1);
              Assert.AreEqual(Udt.SocketState.Listening, server.State);

              using (Udt.Socket accept = server.Accept()) {
            Assert.AreEqual(Udt.SocketState.Open, server.State);
            serverDoneEvent.Set();
            Assert.IsTrue(clientDoneEvent.WaitOne(1000));
              }
            }
              });

              using (Udt.Socket socket = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream))
              {
            Assert.AreEqual(Udt.SocketState.Initial, socket.State);
            Assert.AreEqual(Udt.SocketState.Initial, socket.GetSocketOption(Udt.SocketOptionName.State));
            AssertReadOnly(socket, Udt.SocketOptionName.State);

            socket.Connect(IPAddress.Loopback, port);
            Assert.AreEqual(Udt.SocketState.Connected, socket.State);

            serverDoneEvent.WaitOne(1000);
            clientDoneEvent.Set();

            socket.Close();
            Assert.AreEqual(Udt.SocketState.Closed, socket.State);
            Assert.AreEqual(Udt.SocketState.Closed, socket.GetSocketOption(Udt.SocketOptionName.State));
              }
        }
Пример #19
0
		public void Benchmark()
		{
			//var serializerSource = new Newtonsoft.Json.JsonSerializer();
			var serializer = new ProtobufCommonSerializer();//new JsonCommonSerializer(serializerSource); // 

			var port = new Random().Next(6000, 60000);

			var listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram);
			listener.Bind(IPAddress.Loopback, port);
			listener.Listen(100);
			var serverTransport = listener.GenerateTransportSource(true);
			var serverRouter = new DefaultMessageRouter(serverTransport, serializer);
			serverRouter.AddService<ISumService>(new SumService());

			var client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram);
			client.Connect(IPAddress.Loopback, port);
			var clientTransport = client.GenerateTransportSource(false);
			var clientRouter = new DefaultMessageRouter(clientTransport, serializer);
			var proxy = clientRouter.AddInterface<ISumService>();

			const int randCnt = 100;
			var rand = new Random(42);
			var randoms = new int[randCnt];
			for (int i = 0; i < randCnt; i++) randoms[i] = rand.Next(10000000, 20000000);

			var sw = new Stopwatch();
			long timeFromClient = 0, timeToClient = 0;
			const int cnt = 1000;
			for (int j = 0; j < cnt; j++)
			{
				sw.Start();
				var sum = proxy.Sum(randoms).Result;
				sw.Stop();
				Assert.Equal(randoms.Sum(), sum);
				for (int i = 0; i < randCnt; i++) randoms[i] = rand.Next(10000000, 20000000);
				var times = proxy.TimeDiff(Stopwatch.GetTimestamp()).Result;
				timeFromClient += times.Item1;
				timeToClient += Stopwatch.GetTimestamp() - times.Item2;
			}

			_testOutputHelper.WriteLine("Completed {0} sum passes in {1}ms", cnt, sw.ElapsedMilliseconds);
			_testOutputHelper.WriteLine("Client to server latency: {0}us", timeFromClient / cnt / 10);
			_testOutputHelper.WriteLine("Server to client latency: {0}us", timeToClient / cnt / 10);

			sw.Reset();
			var tree = new SumServiceTree();
			SumServiceTree.FillTree(tree, rand, 2);
			_testOutputHelper.WriteLine("Starting large message transfer.");
			sw.Start();
			var result = proxy.Increment(tree).Result;
			sw.Stop();
			Assert.Equal(tree.Leaf + 1, result.Leaf);
			_testOutputHelper.WriteLine("Completed large transfer in {0}ms", sw.Elapsed.TotalMilliseconds);

			clientRouter.Dispose();
			clientTransport.Dispose();
			client.Dispose();

			serverRouter.Dispose();
			serverTransport.Dispose();
			listener.Dispose();
		}
Пример #20
0
        public void Wait_for_accept()
        {
            using (Udt.SocketPoller poller = new Udt.SocketPoller())
            using (Udt.Socket socket = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream))
            {
                socket.Bind(IPAddress.Loopback, 0);
                socket.Listen(100);
                ManualResetEvent doneEvent = new ManualResetEvent(false);

                poller.AddSocket(socket);

                Task.Factory.StartNew(() =>
                {
                    using (Udt.Socket client = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream))
                    {
                        client.Connect(IPAddress.Loopback, socket.LocalEndPoint.Port);
                        doneEvent.WaitOne(1000);
                    }
                });

                Assert.IsTrue(poller.Wait(TimeSpan.FromSeconds(1)));
                CollectionAssert.AreEqual(new[] { socket }, poller.WriteSockets);
                CollectionAssert.AreEqual(new[] { socket }, poller.ReadSockets);

                Udt.Socket acceptedSocket = socket.Accept();
                acceptedSocket.Dispose();
                doneEvent.Set();

                Assert.IsTrue(poller.Wait(TimeSpan.Zero));
                CollectionAssert.AreEqual(new[] { socket }, poller.WriteSockets);
                CollectionAssert.IsEmpty(poller.ReadSockets);
            }
        }