public EchoServer(SocketFactory factory, int port) { serverWorkers = new EchoServerWorkerFactory(); socket = factory.Tcp(); socket.Bind(port); }
public async Task CanReceiveDataUsingTasksToHostedEchoServer() { string request = "GET /index.html HTTP/1.1\r\nHost: www.example.com\r\n\r\n"; byte[] input = Encoding.ASCII.GetBytes(request); byte[] output = new byte[input.Length]; using (CompletionThread worker = new CompletionThread()) { SocketFactory factory = new SocketFactory(worker); TcpSocket socket = factory.Tcp(); using (EchoServer server = new EchoServer(factory)) { socket.Bind(); worker.Start(); server.Start(); await socket.Connect(server.Endpoint); await socket.Send(input); await socket.Receive(output); Assert.That(input, Is.EqualTo(output)); } } }
public async Task CanHandleTerminatedStream() { IPAddress localhost = IPAddress.Loopback; IPEndPoint endpoint = new IPEndPoint(localhost, 1234); using (CompletionThread worker = new CompletionThread()) { SocketFactory factory = new SocketFactory(worker); using (TcpSocket server = factory.Tcp()) using (TcpSocket socket = factory.Tcp()) { socket.Bind(); worker.Start(); server.Bind(endpoint.Port); server.Listen(1); Task <TcpSocketAccept> acceptable = server.Accept(); await socket.Connect(endpoint); TcpSocketAccept accepted = await acceptable; accepted.Connection.Dispose(); byte[] buffer = new byte[10]; TcpSocketSend sent = await socket.Send(buffer); Assert.That(sent.Status, Is.EqualTo(SocketStatus.OK)); } } }
public void CanSendDataUsingCallbackToExampleSite() { TimeSpan timeout = TimeSpan.FromSeconds(2); ManualResetEvent check = new ManualResetEvent(false); IPAddress[] addresses = Dns.GetHostAddresses("www.example.com"); IPEndPoint endpoint = new IPEndPoint(addresses[0], 80); using (CompletionThread worker = new CompletionThread()) { SocketFactory factory = new SocketFactory(worker); TcpSocket socket = factory.Tcp(); socket.Bind(); worker.Start(); TcpSocketSendCallback onSent = result => { check.Set(); }; TcpSocketConnectCallback onConnected = result => { string request = "GET /index.html HTTP/1.1\r\nHost: www.example.com\r\n\r\n"; byte[] data = Encoding.ASCII.GetBytes(request); socket.Send(data, onSent); }; socket.Connect(endpoint, onConnected); bool completed = check.WaitOne(timeout); Assert.That(completed, Is.True); } }
public ListenerSession(int port, NetworkPool pool) { endpoint = new IPEndPoint(IPAddress.Loopback, port); client = pool.New(); client.Bind(); }
public void CanConnectUsingCallbackToExampleSite() { TimeSpan timeout = TimeSpan.FromSeconds(2); ManualResetEvent check = new ManualResetEvent(false); IPAddress[] addresses = Dns.GetHostAddresses("www.example.com"); IPEndPoint endpoint = new IPEndPoint(addresses[0], 80); using (CompletionThread worker = new CompletionThread()) { SocketFactory factory = new SocketFactory(worker); TcpSocket socket = factory.Tcp(); socket.Bind(); worker.Start(); TcpSocketConnectCallback onConnected = result => { check.Set(); }; socket.Connect(endpoint, onConnected); bool completed = check.WaitOne(timeout); Assert.That(completed, Is.True); } }
public async Task <string> Send(IPEndPoint endpoint, string message) { int progress = 0; byte[] output = new byte[message.Length]; byte[] bytes = Encoding.ASCII.GetBytes(message); using (TcpSocket socket = factory.Tcp()) { socket.Bind(); TcpSocketConnect connected = await socket.Connect(endpoint); TcpSocketSend sent = await socket.Send(bytes); while (progress < output.Length) { SocketBuffer buffer = new SocketBuffer(output, progress); TcpSocketReceive received = await socket.Receive(buffer); if (received.Count == 0) { break; } progress += received.Count; } } return(Encoding.ASCII.GetString(output)); }
public async Task <LoopSession> Start() { int?port; ReceiverService loop = new ReceiverBuilder() .WithDefinition(new LoopMessages()) .Build(hooks); TcpSocket client = pool.New(); TcpSocket server = pool.New(); client.Bind(); server.Bind(out port); server.Listen(1); IPEndPoint endpoint = new IPEndPoint(IPAddress.Loopback, port.Value); Task <TcpSocketAccept> accept = server.Accept(); client.Connect(endpoint, null); PeerHash peer = PeerHash.Random(); TcpSocketAccept accepted = await accept; NetworkConnection receiver = pool.Create(accepted.Connection, NetworkDirection.Incoming, accepted.GetRemote()); loop.StartProcessing(peer, receiver); return(new LoopSession(client, loop)); }
public async Task CanObtainAcceptedRemoteEndpointUsingTasks() { using (CompletionThread worker = new CompletionThread()) { IPEndPoint endpoint; SocketFactory factory = new SocketFactory(worker); using (TcpSocket server = factory.Tcp()) using (TcpSocket client = factory.Tcp()) { worker.Start(); client.Bind(); server.Bind(IPAddress.Loopback); server.Listen(1); endpoint = server.Info().Endpoint; Task <TcpSocketAccept> accepting = server.Accept(); await client.Connect(endpoint); TcpSocketAccept accepted = await accepting; IPEndPoint remote = accepted.GetRemote(); Assert.That(remote.Address, Is.EqualTo(endpoint.Address)); Assert.That(remote.Port, Is.Not.EqualTo(endpoint.Port)); Assert.That(remote.Port, Is.Not.Zero); } } }
public async Task ShouldTriggerConnectionSentWhenSentSomeBytes() { NetworkDirection direction = NetworkDirection.Outgoing; NetworkOutgoingMessage message = new RandomMessage(113); using (NetworkFixture fixture = new NetworkFixture()) using (TcpSocket host = fixture.Pool.New()) using (TcpSocket socket = fixture.Pool.New()) { TcpSocketInfo info = host.BindAndInfo(); int port = info.Endpoint.Port; IPEndPoint endpoint = new IPEndPoint(IPAddress.Loopback, port); socket.Bind(); host.Listen(10); host.Accept(null); await socket.Connect(endpoint); NetworkConnection connection = fixture.Pool.Create(socket, direction, endpoint); Trigger handler = Trigger.Bind(ref fixture.Hooks.OnConnectionSent, data => { data.Remote.Should().Be(NetworkAddress.Parse(endpoint)); data.Connection.Should().Be(connection); data.Bytes.Should().Be(message.Length); }); connection.Send(message); handler.Wait().Should().BeTrue(); } }
///<summary>Processes a SOCKS request from a client.</summary> ///<param name="Request">The request to process.</param> protected override async Task ProcessRequest(byte[] Request) { int Ret; try { if (Request[0] == 1) { // CONNECT IPAddress RemoteIP; int RemotePort = Request[1] * 256 + Request[2]; Ret = Array.IndexOf(Request, (byte)0, 7); Username = Encoding.ASCII.GetString(Request, 7, Ret - 7); if (Request[3] == 0 && Request[4] == 0 && Request[5] == 0 && Request[6] != 0) {// Use remote DNS Ret = Array.IndexOf(Request, (byte)0, Ret + 1); RemoteIP = Dns.GetHostAddressesAsync(Encoding.ASCII.GetString(Request, Username.Length + 8, Ret - Username.Length - 8)).Result[0]; } else { //Do not use remote DNS RemoteIP = IPAddress.Parse(Request[3].ToString() + "." + Request[4].ToString() + "." + Request[5].ToString() + "." + Request[6].ToString()); } RemoteConnection = new TcpSocket(RemoteIP.AddressFamily, false); try { await RemoteConnection.ConnectAsync(new IPEndPoint(RemoteIP, RemotePort)); await OnConnected(null); } catch (Exception ex) { Console.WriteLine("[WARN] " + ex.Message + "\r\n" + ex.StackTrace); await OnConnected(ex); } } else if (Request[0] == 2) { // BIND byte[] Reply = new byte[8]; long LocalIP = BitConverter.ToInt64(Listener.GetLocalExternalIP().Result.GetAddressBytes(), 0); AcceptSocket = new TcpSocket(IPAddress.Any.AddressFamily, false); AcceptSocket.Bind(new IPEndPoint(IPAddress.Any, 0)); AcceptSocket.Listen(50); RemoteBindIP = IPAddress.Parse(Request[3].ToString() + "." + Request[4].ToString() + "." + Request[5].ToString() + "." + Request[6].ToString()); Reply[0] = 0; //Reply version 0 Reply[1] = 90; //Everything is ok :) Reply[2] = (byte)(Math.Floor(((IPEndPoint)AcceptSocket.LocalEndPoint).Port / 256.0)); //Port/1 Reply[3] = (byte)(((IPEndPoint)AcceptSocket.LocalEndPoint).Port % 256); //Port/2 Reply[4] = (byte)((LocalIP % 256)); //IP Address/1 Reply[5] = (byte)(Math.Floor((LocalIP % 65536) / 256.0)); //IP Address/2 Reply[6] = (byte)(Math.Floor((LocalIP % 16777216) / 65536.0)); //IP Address/3 Reply[7] = (byte)(Math.Floor(LocalIP / 16777216.0)); //IP Address/4 await Connection.SendAsync(Reply, async (int x) => { await OnStartAccept(); }); } } catch (Exception ex) { Console.WriteLine("[WARN] " + ex.Message + "\r\n" + ex.StackTrace); await Dispose(ReplyCode.RequestRejected1); } }
public static TcpSocketInfo BindAndInfo(this TcpSocket socket, int port) { if (socket.Bind(port) == false) { return(null); } return(socket.Info()); }
public void CanBindSocket() { using (CompletionThread worker = new CompletionThread()) { SocketFactory factory = new SocketFactory(worker); TcpSocket socket = factory.Tcp(); socket.Bind(); } }
public ConnectorSession(NetworkPool pool, PeerConnector connector) { int?port; this.connector = connector; this.server = pool.New(); server.Bind(out port); server.Listen(1); endpoint = new IPEndPoint(IPAddress.Loopback, port.Value); }
public void Execute(PeerConnectorContext context) { TcpSocket socket = context.Dependencies.Network.New(); IPAddress[] addresses = Dns.GetHostAddresses(remote.Host); IPAddress address = addresses[0].MapToIPv4(); IPEndPoint endpoint = new IPEndPoint(address, remote.Port); socket.Bind(); socket.Connect(endpoint, data => OnConnected(context, data)); }
private void OnSent(TcpSocketSend data) { if (data.Status == SocketStatus.OK) { outgoing = new SocketBuffer(data.Buffer.Data, data.Buffer.Offset + data.Count, data.Buffer.Count - data.Count); if (incoming.Count > 0) { socket.Receive(incoming, OnReceived); } else if (outgoing.Count > 0) { socket.Send(outgoing, OnSent); } else { incoming = new SocketBuffer(incoming.Data); outgoing = new SocketBuffer(outgoing.Data); if (session.Elapsed > TimeSpan.FromMinutes(1)) { socket = factory.Tcp(); session = Stopwatch.StartNew(); socket.Bind(); socket.Connect(endpoint, OnConnected); data.Socket.Dispose(); } else { socket.Send(outgoing, OnSent); } } } else { Console.WriteLine("OnSent"); socket.Dispose(); } counter += data.Count; if (counter - previous > 1024 * 1024 * 1024) { previous = counter; Console.WriteLine($"{counter}: {counter / watch.ElapsedMilliseconds}"); } }
public static bool Bind(this TcpSocket socket, out int?port) { TcpSocketInfo info; if (socket.Bind() == false) { port = null; return(false); } info = socket.Info(); port = info.Endpoint.Port; return(true); }
public bool Start(int port, out string err, string host = null) { Socket s = TcpSocket.CreateSocket(); err = string.Empty; try { TcpSocket.Bind(s, port, out string msg, host); s.Listen(5); } catch (Exception e) { err = $"启动socket服务时出现异常:{e.Message}"; return(false); } m_ServerSocket = s; Accept(s); return(true); }
///<summary>Starts listening on the selected IP address and port.</summary> ///<exception cref="SocketException">There was an error while creating the listening socket.</exception> public async void Start() { try { ListenSocket = new TcpSocket(Address.AddressFamily, this.Secure); ListenSocket.Bind(new IPEndPoint(Address, Port)); ListenSocket.Listen(50); SocketConnection socket = await ListenSocket.AcceptAsync(); await this.OnAccept(socket); } catch (Exception ex) { Console.WriteLine("[WARN] " + ex.Message + "\r\n" + ex.StackTrace); this.Dispose(); throw new SocketException(); } }
public async Task ShouldTriggerConnectionReceivedWhenReceivedSomeBytes() { NetworkDirection direction = NetworkDirection.Outgoing; NetworkOutgoingMessage message = new RandomMessage(113); using (NetworkFixture fixture = new NetworkFixture()) using (TcpSocket host = fixture.Pool.New()) using (TcpSocket socket = fixture.Pool.New()) { TcpSocketInfo info = host.BindAndInfo(); int port = info.Endpoint.Port; IPEndPoint endpoint = new IPEndPoint(IPAddress.Loopback, port); socket.Bind(); host.Listen(10); Task <TcpSocketAccept> task = host.Accept(); await socket.Connect(endpoint); TcpSocketAccept accept = await task; NetworkConnection connection = fixture.Pool.Create(socket, direction, endpoint); NetworkBlock block = new NetworkBlock(new byte[1024], 0, message.Length); Trigger handler = Trigger.Bind(ref fixture.Hooks.OnConnectionReceived, data => { data.Remote.Should().Be(NetworkAddress.Parse(endpoint)); data.Connection.Should().NotBeNull(); data.Bytes.Should().Be(message.Length); }); connection.Receive(new NullReceiver()); message.ToBytes(block); block.With((buffer, offset, count) => { accept.Connection.Send(new SocketBuffer(buffer, offset, count), null); }); handler.Wait().Should().BeTrue(); } }
public async Task CanConnectUsingTasksToNotAvailableSite() { IPAddress[] addresses = Dns.GetHostAddresses("www.example.com"); IPEndPoint endpoint = new IPEndPoint(addresses[0], 8123); using (CompletionThread worker = new CompletionThread()) { SocketFactory factory = new SocketFactory(worker); TcpSocket socket = factory.Tcp(); socket.Bind(); worker.Start(); TcpSocketConnect connect = await socket.Connect(endpoint); SocketStatus expected = SocketStatus.TimedOut; Assert.That(connect.Status, Is.EqualTo(expected)); } }
public async Task <NegotiatorFixturePair> Create() { int?port; TcpSocket host = pool.New(); TcpSocket client = pool.New(); client.Bind(); host.Bind(out port); host.Listen(1); Task <TcpSocketAccept> accept = host.Accept(); Task <TcpSocketConnect> connect = client.Connect(port.Value); TcpSocketAccept accepted = await accept; TcpSocketConnect connected = await connect; NetworkConnection local = pool.Create(connected.Socket, NetworkDirection.Outgoing, connected.Endpoint); NetworkConnection remote = pool.Create(accepted.Connection, NetworkDirection.Incoming, accepted.GetRemote()); return(new NegotiatorFixturePair(local, remote)); }
public async Task CanSendDataUsingAsyncToExampleSite() { IPAddress[] addresses = Dns.GetHostAddresses("www.example.com"); IPEndPoint endpoint = new IPEndPoint(addresses[0], 80); string request = "GET /index.html HTTP/1.1\r\nHost: www.example.com\r\n\r\n"; byte[] data = Encoding.ASCII.GetBytes(request); using (CompletionThread worker = new CompletionThread()) { SocketFactory factory = new SocketFactory(worker); TcpSocket socket = factory.Tcp(); socket.Bind(); worker.Start(); await socket.Connect(endpoint); await socket.Send(data); } }
public async Task ShouldTriggerConnectionTerminatedWhenSending() { NetworkDirection direction = NetworkDirection.Outgoing; using (NetworkFixture fixture = new NetworkFixture()) using (TcpSocket host = fixture.Pool.New()) using (TcpSocket socket = fixture.Pool.New()) { TcpSocketInfo info = host.BindAndInfo(); int port = info.Endpoint.Port; IPEndPoint endpoint = new IPEndPoint(IPAddress.Loopback, port); socket.Bind(); host.Listen(10); Task <TcpSocketAccept> task = host.Accept(); TcpSocketConnect connect = await socket.Connect(endpoint); TcpSocketAccept accept = await task; connect.Status.Should().Be(SocketStatus.OK); accept.Status.Should().Be(SocketStatus.OK); accept.Connection.Dispose(); NetworkConnection connection = fixture.Pool.Create(socket, direction, endpoint); Trigger handler = Trigger.Bind(ref fixture.Hooks.OnConnectionTerminated, data => { data.Remote.Should().Be(NetworkAddress.Parse(endpoint)); data.Connection.Should().NotBeNull(); }); for (int i = 0; i < 10; i++) { connection.Send(new OneByteMessage()); } handler.Wait().Should().BeTrue(); } }
public EchoServer(SocketFactory factory) { socket = factory.Tcp(); socket.Bind(IPAddress.Loopback); }
public static TcpSocketInfo BindAndInfo(this TcpSocket socket) { socket.Bind(); return(socket.Info()); }
public void Start() { socket.Bind(); socket.Connect(endpoint, OnConnected); }
///<summary>Processes a received query.</summary> ///<param name="Query">The query to process.</param> private async Task ProcessQuery(byte[] Query) { try { Request request = null; Request.ParseRequest(Query, out request); switch (request.Command) { case Command.Connect: //CONNECT IPAddress RemoteIP = request.DstAddr; int RemotePort = 0; if (Query[3] == 1) { RemoteIP = IPAddress.Parse(Query[4].ToString() + "." + Query[5].ToString() + "." + Query[6].ToString() + "." + Query[7].ToString()); RemotePort = Query[8] * 256 + Query[9]; } else if (Query[3] == 3) { if (RemoteIP == null) { RemoteIP = Dns.GetHostAddressesAsync(Encoding.ASCII.GetString(Query, 5, Query[4])).Result[0]; } RemotePort = Query[4] + 5; RemotePort = Query[RemotePort] * 256 + Query[RemotePort + 1]; } RemoteConnection = new TcpSocket(RemoteIP.AddressFamily, false); try { await RemoteConnection.ConnectAsync(new IPEndPoint(RemoteIP, RemotePort)); await OnConnected(null); } catch (SocketException ex) { Console.WriteLine("[WARN] SocketError=" + ex.SocketErrorCode + "\r\n"); await OnConnected(ex); } catch (Exception ex) { Console.WriteLine("[WARN] " + ex.Message + "\r\n" + ex.StackTrace); await OnConnected(ex); } break; case Command.Bind: //BIND byte[] Reply = new byte[10]; long LocalIP = BitConverter.ToInt64(Listener.GetLocalExternalIP().Result.GetAddressBytes(), 0); AcceptSocket = new TcpSocket(IPAddress.Any.AddressFamily, false); AcceptSocket.Bind(new IPEndPoint(IPAddress.Any, 0)); AcceptSocket.Listen(50); Reply[0] = 5; //Version 5 Reply[1] = 0; //Everything is ok :) Reply[2] = 0; //Reserved Reply[3] = 1; //We're going to send a IPv4 address Reply[4] = (byte)((LocalIP % 256)); //IP Address/1 Reply[5] = (byte)((LocalIP % 65536) / 256); //IP Address/2 Reply[6] = (byte)((LocalIP % 16777216) / 65536); //IP Address/3 Reply[7] = (byte)(Math.Floor(LocalIP / 16777216.0)); //IP Address/4 Reply[8] = (byte)(Math.Floor(((IPEndPoint)AcceptSocket.LocalEndPoint).Port / 256.0)); //Port/1 Reply[9] = (byte)(((IPEndPoint)AcceptSocket.LocalEndPoint).Port % 256); //Port/2 await Connection.SendAsync(Reply, async (int x) => { await this.OnStartAccept(); }); break; case Command.UdpAssociate: //UDP ASSOCIATE if (request.DstAddr.Equals(IPAddress.Any) && request.DstPort == 0) { request.DstPort = FreePort.FindNextAvailableUDPPort(4200); if (request.DstPort == 0) { await Dispose(ReplyCode.SocksFailure); return; } } if (request.DstAddr.Equals(IPAddress.Any)) { request.DstAddr = ((IPEndPoint)Connection.LocalEndPoint).Address; } UdpClientEndPoint = new IPEndPoint(request.DstAddr, request.DstPort); LocalBindEndPoint = new IPEndPoint(((IPEndPoint)(Connection.LocalEndPoint)).Address, request.DstPort); var reply = request.CreateReply(LocalBindEndPoint.Address, LocalBindEndPoint.Port); await Connection.SendAsync(reply.ToBytes(), async (int x) => { await this.StartUdpReceive(); }); break; default: await Dispose(ReplyCode.UnsupportedCommand); break; } } catch (Exception ex) { Console.WriteLine("[WARN] " + ex.Message + "\r\n" + ex.StackTrace); await Dispose(ReplyCode.SocksFailure); } }