public void Bind_IPAddress_int__BindTwice() { int port = _portNum++; using (Udt.Socket socket = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream)) { socket.Bind(IPAddress.Any, port); Udt.SocketException error = Assert.Throws <Udt.SocketException>(() => { socket.Bind(IPAddress.Any, port); }); Assert.AreEqual(Udt.SocketError.InvalidOperation, error.SocketErrorCode); } port = _portNum++; if (Socket.OSSupportsIPv6) { using (Udt.Socket socket = new Udt.Socket(AddressFamily.InterNetworkV6, SocketType.Stream)) { socket.Bind(IPAddress.IPv6Any, port); Udt.SocketException error = Assert.Throws <Udt.SocketException>(() => { socket.Bind(IPAddress.IPv6Any, port); }); Assert.AreEqual(Udt.SocketError.InvalidOperation, error.SocketErrorCode); } } }
public void Bind_IPEndPoint__InvalidArgs() { Udt.Socket socket = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream); // endPoint ArgumentException ex = Assert.Throws <ArgumentNullException>(() => socket.Bind((IPEndPoint)null)); Assert.AreEqual("endPoint", ex.ParamName); // address type different from family passed to constructor ex = Assert.Throws <ArgumentException>(() => socket.Bind(new IPEndPoint(IPAddress.IPv6Any, 10000))); Assert.AreEqual("endPoint", ex.ParamName); }
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(); }
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(); }
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); } }
public void Bind_IPEndPoint() { int port = _portNum++; using (Udt.Socket socket = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream)) { socket.Bind(new IPEndPoint(IPAddress.Any, port)); IPEndPoint localEP = socket.LocalEndPoint; Assert.AreEqual(IPAddress.Any, localEP.Address); Assert.AreEqual(port, localEP.Port); } if (Socket.OSSupportsIPv6) { port = _portNum++; using (Udt.Socket socket = new Udt.Socket(AddressFamily.InterNetworkV6, SocketType.Stream)) { socket.Bind(new IPEndPoint(IPAddress.IPv6Any, port)); IPEndPoint localEP = socket.LocalEndPoint; Assert.AreEqual(IPAddress.IPv6Any, localEP.Address); Assert.AreEqual(port, localEP.Port); } } }
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(); }
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(); }
public void Start() { try { if (started) { LOGGER.Error("Already started"); } started = true; socket = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream); socket.Bind(IPAddress.Any, port); LOGGER.Info("server started with port: " + port); ListenPeers(); } catch (Exception ex) { LOGGER.Error("Socket Loop Exception", ex); throw ex; } finally { started = false; ShutdownSocket(); } }
public UdtListener(IPEndPoint bindAddress) : this( new Udt.Socket( System.Net.Sockets.AddressFamily.InterNetwork, //IPv4 System.Net.Sockets.SocketType.Stream //UDP ) ) { //Do nothing udtSocket.Bind(bindAddress); }
public void Listen() { int port = _portNum++; using (Udt.Socket socket = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream)) { socket.Bind(IPAddress.Any, port); socket.Listen(1); // What condition to assert here? } }
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; }
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(); }
public void Bind_IPAddress_int__AfterClosed() { int port = _portNum++; Udt.Socket socket = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream); socket.Dispose(); Assert.Throws <ObjectDisposedException>(() => { socket.Bind(IPAddress.Any, port); }); }
public void Bind_IPAddress_int() { int port = _portNum++; using (Udt.Socket socket = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream)) { socket.Bind(IPAddress.Any, port); IPEndPoint localEP = socket.LocalEndPoint; Assert.AreEqual(IPAddress.Any, localEP.Address); Assert.AreEqual(port, localEP.Port); } }
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); }
public IPEndPoint WaitForSync(PeerInfo peer, String syncId, List <SyncType> syncTypes = null) { var syncer = new Syncer(syncId, syncTypes); var activeIp = syncer.WaitForSyncFromPeer(peer, 60000, _udpClient); ListeningSocket = SetupUdtSocket(); ListeningSocket.Bind(_udpClient.Client); ListeningSocket.Listen(10); Udt.Socket udtClient = ListeningSocket.Accept(); UdtConnection = udtClient; UdtConnection.BlockingReceive = true; Logger.Debug("Successfully completed incoming tunnel with " + activeIp + "-" + syncId); return(activeIp); }
public void Bind_IPAddress_int__InvalidArgs() { Udt.Socket socket = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream); // address ArgumentException ex = Assert.Throws <ArgumentNullException>(() => socket.Bind(null, 1)); Assert.AreEqual("address", ex.ParamName); // address type different from family passed to constructor ex = Assert.Throws <ArgumentException>(() => socket.Bind(IPAddress.IPv6Any, 10000)); Assert.AreEqual("address", ex.ParamName); // port ArgumentOutOfRangeException argEx = Assert.Throws <ArgumentOutOfRangeException>(() => socket.Bind(IPAddress.Any, -1)); Assert.AreEqual("port", argEx.ParamName); Assert.AreEqual(-1, argEx.ActualValue); argEx = Assert.Throws <ArgumentOutOfRangeException>(() => socket.Bind(IPAddress.Any, 65536)); Assert.AreEqual("port", argEx.ParamName); Assert.AreEqual(65536, argEx.ActualValue); }
public void Remove_socket() { 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); Assert.IsFalse(poller.Wait(TimeSpan.Zero)); poller.RemoveSocket(socket); Assert.Throws<InvalidOperationException>(() => poller.Wait(TimeSpan.Zero)); } }
public void Remove_socket() { 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); Assert.IsFalse(poller.Wait(TimeSpan.Zero)); poller.RemoveSocket(socket); Assert.Throws <InvalidOperationException>(() => poller.Wait(TimeSpan.Zero)); } }
public void Bind_IPAddress_int__IPV6() { if (!Socket.OSSupportsIPv6) { Assert.Ignore("OS does not support IPv6"); } int port = _portNum++; using (Udt.Socket socket = new Udt.Socket(AddressFamily.InterNetworkV6, SocketType.Stream)) { socket.Bind(IPAddress.IPv6Any, port); IPEndPoint localEP = socket.LocalEndPoint; Assert.AreEqual(IPAddress.IPv6Any, localEP.Address); Assert.AreEqual(port, localEP.Port); } }
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(); }
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(); }
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)); } }
public void Bind_IPEndPoint__InvalidArgs() { Udt.Socket socket = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream); // endPoint ArgumentException ex = Assert.Throws<ArgumentNullException>(() => socket.Bind((IPEndPoint)null)); Assert.AreEqual("endPoint", ex.ParamName); // address type different from family passed to constructor ex = Assert.Throws<ArgumentException>(() => socket.Bind(new IPEndPoint(IPAddress.IPv6Any, 10000))); Assert.AreEqual("endPoint", ex.ParamName); }
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)); } }
public void Listen() { int port = _portNum++; using (Udt.Socket socket = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream)) { socket.Bind(IPAddress.Any, port); socket.Listen(1); // What condition to assert here? } }
public void Bind_IPAddress_int__AfterClosed() { int port = _portNum++; Udt.Socket socket = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream); socket.Dispose(); Assert.Throws<ObjectDisposedException>(() => { socket.Bind(IPAddress.Any, port); }); }
public void Bind_IPAddress_int__IPV6() { if (!Socket.OSSupportsIPv6) { Assert.Ignore("OS does not support IPv6"); } int port = _portNum++; using (Udt.Socket socket = new Udt.Socket(AddressFamily.InterNetworkV6, SocketType.Stream)) { socket.Bind(IPAddress.IPv6Any, port); IPEndPoint localEP = socket.LocalEndPoint; Assert.AreEqual(IPAddress.IPv6Any, localEP.Address); Assert.AreEqual(port, localEP.Port); } }
static int Main(string[] args) { if ((1 < args.Length) || ((1 == args.Length) && (0 == int.Parse(args[0])))) { Console.WriteLine("Usage: SendFile [ServerPort]"); return(1); } try { using (Udt.Socket server = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream)) { int port = 9000; if (1 == args.Length) { port = int.Parse(args[0]); } server.Bind(IPAddress.Any, port); Console.WriteLine("Server is ready at port: {0}", port); server.Listen(1); using (Udt.Socket client = server.Accept()) { server.Close(); // Receive file name from client byte[] file = new byte[1024]; int length; string name; client.Receive(file, 0, sizeof(int)); length = BitConverter.ToInt32(file, 0); client.Receive(file, 0, length); name = Encoding.UTF8.GetString(file, 0, length); // Send file size information client.Send(BitConverter.GetBytes(new FileInfo(name).Length), 0, sizeof(long)); Udt.TraceInfo trace = client.GetPerformanceInfo(); // Send the file client.SendFile(name); trace = client.GetPerformanceInfo(); PrintProps("Total", trace.Total); PrintProps("Local", trace.Local); PrintProps("Probe", trace.Probe); client.Close(); } } Console.ReadKey(true); return(0); } catch (Exception ex) { Console.Error.WriteLine("Error sending file: {0}", ex.Message); Console.ReadKey(true); return(2); } }
/// <summary> /// Creates a new UDT over UDP socket, and binds the socket to the address given. /// </summary> /// <param name="endpoint">Endpoint to bind to.</param> public UdtSocket(IPEndPoint bindAddress) : this() { //Connect to the endpoint given. udtSocket.Bind(bindAddress); }
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(); }
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(); }
public void Bind_IPAddress_int__InvalidArgs() { Udt.Socket socket = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream); // address ArgumentException ex = Assert.Throws<ArgumentNullException>(() => socket.Bind(null, 1)); Assert.AreEqual("address", ex.ParamName); // address type different from family passed to constructor ex = Assert.Throws<ArgumentException>(() => socket.Bind(IPAddress.IPv6Any, 10000)); Assert.AreEqual("address", ex.ParamName); // port ArgumentOutOfRangeException argEx = Assert.Throws<ArgumentOutOfRangeException>(() => socket.Bind(IPAddress.Any, -1)); Assert.AreEqual("port", argEx.ParamName); Assert.AreEqual(-1, argEx.ActualValue); argEx = Assert.Throws<ArgumentOutOfRangeException>(() => socket.Bind(IPAddress.Any, 65536)); Assert.AreEqual("port", argEx.ParamName); Assert.AreEqual(65536, argEx.ActualValue); }
public IPEndPoint WaitForSync(PeerInfo peer, String syncId, List<SyncType> syncTypes = null) { var syncer = new Syncer(syncId, syncTypes); var activeIp = syncer.WaitForSyncFromPeer(peer, 60000, _udpClient); ListeningSocket = SetupUdtSocket(); ListeningSocket.Bind(_udpClient.Client); ListeningSocket.Listen(10); Udt.Socket udtClient = ListeningSocket.Accept(); UdtConnection = udtClient; UdtConnection.BlockingReceive = true; Logger.Debug("Successfully completed incoming tunnel with " + activeIp + "-" + syncId); return activeIp; }
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(); }
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); } }
static int Main(string[] args) { if ((1 < args.Length) || ((1 == args.Length) && (0 == int.Parse(args[0])))) { Console.WriteLine("Usage: SendFile [ServerPort]"); return 1; } try { using (Udt.Socket server = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream)) { int port = 9000; if (1 == args.Length) port = int.Parse(args[0]); server.Bind(IPAddress.Any, port); Console.WriteLine("Server is ready at port: {0}", port); server.Listen(1); using (Udt.Socket client = server.Accept()) { server.Close(); // Receive file name from client byte[] file = new byte[1024]; int length; string name; client.Receive(file, 0, sizeof(int)); length = BitConverter.ToInt32(file, 0); client.Receive(file, 0, length); name = Encoding.UTF8.GetString(file, 0, length); // Send file size information client.Send(BitConverter.GetBytes(new FileInfo(name).Length), 0, sizeof(long)); Udt.TraceInfo trace = client.GetPerformanceInfo(); // Send the file client.SendFile(name); trace = client.GetPerformanceInfo(); PrintProps("Total", trace.Total); PrintProps("Local", trace.Local); PrintProps("Probe", trace.Probe); client.Close(); } } Console.ReadKey(true); return 0; } catch (Exception ex) { Console.Error.WriteLine("Error sending file: {0}", ex.Message); Console.ReadKey(true); return 2; } }
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(); }
public void Bind_IPAddress_int__BindTwice() { int port = _portNum++; using (Udt.Socket socket = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream)) { socket.Bind(IPAddress.Any, port); Udt.SocketException error = Assert.Throws<Udt.SocketException>(() => { socket.Bind(IPAddress.Any, port); }); Assert.AreEqual(Udt.SocketError.InvalidOperation, error.SocketErrorCode); } port = _portNum++; if (Socket.OSSupportsIPv6) { using (Udt.Socket socket = new Udt.Socket(AddressFamily.InterNetworkV6, SocketType.Stream)) { socket.Bind(IPAddress.IPv6Any, port); Udt.SocketException error = Assert.Throws<Udt.SocketException>(() => { socket.Bind(IPAddress.IPv6Any, port); }); Assert.AreEqual(Udt.SocketError.InvalidOperation, error.SocketErrorCode); } } }
internal static void RecieveFiles(NetIncomingMessage msg) { Udt.Socket socket = new Udt.Socket(AddressFamily.InterNetwork, SocketType.Stream); socket.Bind(IPAddress.Any, 10000); socket.Listen(10); Udt.Socket client = socket.Accept(); // Receive the file length, in bytes byte[] buffer = new byte[8]; client.Receive(buffer, 0, sizeof(long)); // Receive the file contents (path is where to store the file) client.ReceiveFile("hello.txt", BitConverter.ToInt64(buffer, 0)); Console.WriteLine("OI!"); }