// ReSharper restore FunctionNeverReturns

        public async Task AcceptLoopReuseAcceptContext()
        {
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Bind(new IPEndPoint(IPAddress.Loopback, 40040));
            socket.Listen(10);
            var context = new AcceptSocketAsyncContext();
            do
            {
                await socket.AcceptTaskAsync(context).ContinueWith(
                    async task =>
                        {
                            using (var socketAccept = task.Result)
                            {
                                var buffer = new byte[4096];
                                var received =
                                    await socketAccept.ReceiveTaskAsync(buffer, 0, buffer.Length, SocketFlags.None);
                                socketAccept.Shutdown(SocketShutdown.Receive);
                                await socketAccept.SendTaskAsync(buffer, 0, received, SocketFlags.None);
                                socketAccept.Shutdown(SocketShutdown.Both);
                                socketAccept.Close();
                            }
                        }
                    );
            } while (true);
// ReSharper disable FunctionNeverReturns
        }
Beispiel #2
0
        public async Task StartListen(int port)
        {
            if (_listenSocket != null)
            {
                throw new Exception("Already started. Please stop it first.");
            }

            if (NetUtils.IsPortInUse(port))
            {
                throw new SocketException((int)SocketError.AddressAlreadyInUse);
            }

            ListenEp.Port = port;

            try {
                _listenSocket = new Socket(ListenEp.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                _listenSocket.Bind(ListenEp);
                _listenSocket.Listen(100);
                logger.Info("Start Proxy On  " + ListenEp);
            } catch (SocketException ex) {
                logger.Error("Listen failed. " + ex.SocketErrorCode);
                Stop();
                throw;
            }

            try {
                while (true)
                {
                    Socket requestSocket =
                        await _listenSocket.AcceptTaskAsync().ConfigureAwait(false);

                    ProxyConnection newConn = new SocksProxyConnection(requestSocket);

                    //StartHandshake处理了所有的异常,不会有异常抛出。
                    //所以无限循环只能在AcceptTaskAsync失败(如Stop())时结束
                    await newConn.StartHandshake();
                }
            } catch (ObjectDisposedException) {
                //// Stop() cause this exception, and this task finished.
                //ignore
            } catch (SocketException ex) {
                logger.Error("Accept failed. " + ex.SocketErrorCode);
                Stop();
                throw;
            } catch (Exception ex) {
                logger.Error("Accept failed." + ex.TypeAndMessage());
                Stop();
                throw;
            }
        }
        public async Task AcceptReciveSendLoopFullSync()
        {
            var socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
            socket.Bind( new IPEndPoint( IPAddress.Loopback, 40020));
            socket.Listen(10);
            do
            {
                using (var acceptSocket = await socket.AcceptTaskAsync())
                {
                    var buffer = new byte[4096];

                    var received = await acceptSocket.ReceiveTaskAsync(buffer, 0, buffer.Length, SocketFlags.None);
                    acceptSocket.Shutdown(SocketShutdown.Receive);
                    await acceptSocket.SendTaskAsync( buffer,received, SocketFlags.None);
                    acceptSocket.Shutdown(SocketShutdown.Both);
                    acceptSocket.Close();
                }
            } while (true);
// ReSharper disable FunctionNeverReturns
        }
Beispiel #4
0
        void AcceptConnection()
        {
            Task <Socket> waitConnectionTask = socketServer.AcceptTaskAsync();

            waitConnectionTask.ContinueWith(async task =>
            {
                Socket socketClient = task.Result;

                if (task.Exception == null)
                {
                    if (isActive)
                    {
                        AcceptConnection();
                    }

                    Logger.Write(Source.Server, $"Новое подключение. Удалённая конечная точка: {socketClient.RemoteEndPoint}");

                    await StartPreprocessingConnection(socketClient).ConfigureAwait(false);
                }
            });
        }
Beispiel #5
0
        public void AcceptAsync()
        {
            using (var socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp))
            {
                EndPoint localEp = new IPEndPoint(IPAddress.Loopback, 40001);
                socket.Bind(localEp);
                socket.Listen(10);
                var task = socket.AcceptTaskAsync();
                using (var connSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    var cont = task.ContinueWith(t =>
                        {
                            var acceptSocket = t.Result;
                            acceptSocket.RemoteEndPoint.Is(connSocket.LocalEndPoint);
                            acceptSocket.Close();
                        });
                    connSocket.Connect(localEp);

                    cont.Wait();
                }
            }
        }
Beispiel #6
0
        public async Task ListenAsync(CancellationToken cancellationToken)
        {
            var sock = new Socket(SocketType.Stream, ProtocolType.Tcp);

            sock.Bind(new IPEndPoint(IPAddress.Loopback, 0));
            sock.Listen(50);

            cancellationToken.Register(sock.Close);

            logger.LogInformation("Listening on {0}", sock.LocalEndPoint);

            while (!cancellationToken.IsCancellationRequested)
            {
                Socket socket = default;
                try
                {
                    socket = await sock.AcceptTaskAsync().ConfigureAwait(false);
                }
                catch (ObjectDisposedException) when(cancellationToken.IsCancellationRequested)
                {
                }

                if (socket != null)
                {
                    var handler = new SocketHandler(loggerFactory.CreateLogger <SocketHandler>(), parameters, socket);
                    logger.LogDebug("Accepted new socket {0} => {1} for handler {2}", socket.RemoteEndPoint, socket.LocalEndPoint, handler.Identifier);

                    handlers[handler.Identifier] = handler;
                    var task = handler.HandleAsync(cancellationToken);
                    _ = task.ContinueWith(t => FinishConnection(handler.Identifier, t));
                }
            }

            while (!handlers.IsEmpty)
            {
                logger.LogDebug("Waiting for all handlers to clean up. {0} remaining...", handlers.Count);
                await Task.Delay(TimeSpan.FromMilliseconds(10));
            }
        }
Beispiel #7
0
 public void AcceptAsyncWithAcceptSocketClose()
 {
     using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
     {
         EndPoint localEp = new IPEndPoint(IPAddress.Loopback, 40000);
         socket.Bind(localEp);
         socket.Listen(10);
         var task = socket.AcceptTaskAsync();
         task.IsCompleted.IsFalse();
         socket.Close();
         try
         {
             task.Wait();
             Assert.Fail("unexpected Success");
         }
         catch (AggregateException e)
         {
             e.InnerExceptions.Count.Is(1);
             e.InnerExceptions[0].IsInstanceOf<AsyncSocketErrorException>()
                 .SocketError.Is(SocketError.OperationAborted);
         }
     }
 }
        async Task <Result <Socket> > AcceptConnectionFromRemoteServerAsync(CancellationToken token)
        {
            Result <Socket> acceptConnection;

            try
            {
                acceptConnection = await _listenSocket.AcceptTaskAsync(token).ConfigureAwait(false);
            }
            catch (TaskCanceledException ex)
            {
                ReportError(ex.GetReport());
                return(Result.Fail <Socket>(ex.GetReport()));
            }
            catch (SocketException ex)
            {
                ReportError(ex.GetReport());
                return(Result.Fail <Socket>(ex.GetReport()));
            }

            if (acceptConnection.Failure)
            {
                ReportError(acceptConnection.Error);
                return(Result.Fail <Socket>(acceptConnection.Error));
            }

            var socket = acceptConnection.Value;
            var remoteServerIpString  = socket.RemoteEndPoint.ToString().Split(':')[0];
            var remoteServerIpAddress = NetworkUtilities.ParseSingleIPv4Address(remoteServerIpString).Value;

            EventOccurred?.Invoke(this, new ServerEvent
            {
                EventType             = EventType.ConnectionAccepted,
                RemoteServerIpAddress = remoteServerIpAddress
            });

            return(Result.Ok(socket));
        }
Beispiel #9
0
 public Task <Socket> AcceptAsync()
 {
     return(_socket.AcceptTaskAsync());
 }
 Task <Result <Socket> > AcceptConnectionTask()
 {
     return(_listenSocket.AcceptTaskAsync(new CancellationToken()));
 }