예제 #1
0
        private async void CreateInternalServer()
        {
            InternalServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            {
                ReceiveTimeout      = ReadWriteTimeOut,
                SendTimeout         = ReadWriteTimeOut,
                ExclusiveAddressUse = true
            };

            InternalServer.Bind(new IPEndPoint(IPAddress.Loopback, 0));

            InternalPort = ((IPEndPoint)(InternalServer.LocalEndPoint)).Port;
            InternalUri  = new Uri($"http://127.0.0.1:{InternalPort}");

            InternalServer.Listen(512);

            while (!IsDisposed)
            {
                try
                {
                    Socket InternalClient = await InternalServer?.AcceptAsync();

                    if (InternalClient != null)
                    {
                        _ = HandleClient(InternalClient);
                    }
                }
                catch
                {
                    //? Ignore dispose intrnal server
                }
            }
        }
예제 #2
0
파일: Shutdown.cs 프로젝트: nnyamhon/corefx
        public void Shutdown_TCP_CLOSED_Success()
        {
            // NOTE: this value should technically be at least as long as the amount
            //       of time that a TCP connection will stay in the TIME_WAIT state.
            //       That value, however, is technically defined as 2 * MSL, which is
            //       officially 4 minutes, and may differ between systems. In practice,
            //       5 seconds has proved to be long enough.
            const int TimeWaitTimeout = 5000;

            using (Socket server = new Socket(SocketType.Stream, ProtocolType.Tcp))
            using (Socket client = new Socket(SocketType.Stream, ProtocolType.Tcp))
            {
                int port = server.BindToAnonymousPort(IPAddress.IPv6Any);
                server.Listen(1);

                var args = new SocketAsyncEventArgs();
                args.Completed += OnOperationCompleted;
                Assert.True(server.AcceptAsync(args));

                client.Connect(IPAddress.IPv6Loopback, port);

                var buffer = new byte[] { 42 };
                for (int i = 0; i < 32; i++)
                {
                    int sent = client.Send(buffer);
                    Assert.Equal(1, sent);
                }

                client.Shutdown(SocketShutdown.Send);

                int received = 0;
                do
                {
                    received = client.Receive(buffer);
                } while (received != 0);

                // Wait for the underlying connection to transition from TIME_WAIT to
                // CLOSED.
                Task.Delay(TimeWaitTimeout).Wait();

                client.Shutdown(SocketShutdown.Both);
            }
        }
예제 #3
0
        public async Task ReuseSocketAsyncEventArgs_SameInstance_MultipleSockets()
        {
            using (var listen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                listen.Bind(new IPEndPoint(IPAddress.Loopback, 0));
                listen.Listen(1);

                Task<Socket> acceptTask = listen.AcceptAsync();
                await Task.WhenAll(
                    acceptTask,
                    client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listen.LocalEndPoint).Port)));

                using (Socket server = await acceptTask)
                {
                    TaskCompletionSource<bool> tcs = null;

                    var args = new SocketAsyncEventArgs();
                    args.SetBuffer(new byte[1024], 0, 1024);
                    args.Completed += (_,__) => tcs.SetResult(true);

                    for (int i = 1; i <= 10; i++)
                    {
                        tcs = new TaskCompletionSource<bool>();
                        args.Buffer[0] = (byte)i;
                        args.SetBuffer(0, 1);
                        if (server.SendAsync(args))
                        {
                            await tcs.Task;
                        }

                        args.Buffer[0] = 0;
                        tcs = new TaskCompletionSource<bool>();
                        if (client.ReceiveAsync(args))
                        {
                            await tcs.Task;
                        }
                        Assert.Equal(1, args.BytesTransferred);
                        Assert.Equal(i, args.Buffer[0]);
                    }
                }
            }
        }
예제 #4
0
        public void StartListen(SocketAsyncEventArgs saea)
        {
            if (saea == null)
            {
                saea = new SocketAsyncEventArgs();
            }
            else
            {
                saea.AcceptSocket = null;//初始化清空;
            }

            saea.Completed += Acction;           //saea.Completed回调程序,在完成监听的时候执行委托
            bool jim = socket.AcceptAsync(saea); //这里线程不会阻塞,但异步线程正在等待用户接入,等到用户接入时,就会调用saea.Completed;

            //判断异步是否挂起
            //true   挂起监听,如果挂起表示我们没有立刻收到客户端的链接,(假阻塞)需要等待客户端接入进来,通过Completed事件通知服务器有客户端接入进来
            //false  没有挂起,没有挂起表示我们立刻收到了客户端链接,不会执行saea.Completed这个回调程序,所以需要自己手动执行
            if (!jim)                //取反,如果jim为true,这里就为false条件,反之为true条件;因为当jim为false时,需要执行下面方法;但是只有if(ture)才会执行,这里就绕了一下;相当于if(jim==false){};
            {
                ListenTheUser(saea); //同步完成
            }
        }
예제 #5
0
        private void Accepted(object sender, SocketAsyncEventArgs eventArgs)
        {
            try
            {
                Socket acceptedSocket = eventArgs.AcceptSocket;
                if (acceptedSocket.Connected == false)
                {
                    return;
                }


                Session acceptedSession = _networkChannel.PopInactiveSession();
                if (acceptedSession == null)
                {
                    acceptedSocket.Close();
                    Logger.Err(LogMask.Aegis, "Cannot activate any more sessions. Please check MaxSessionPoolSize.");
                    return;
                }


                acceptedSession.AttachSocket(acceptedSocket);
                acceptedSession.OnSocket_Accepted();


                eventArgs.AcceptSocket = null;
                _listenSocket.AcceptAsync(_eventAccept);
            }
            catch (SocketException e)
            {
                if (e.SocketErrorCode != SocketError.Interrupted)
                {
                    Logger.Err(LogMask.Aegis, e.ToString());
                }
            }
            catch (Exception e)
            {
                Logger.Err(LogMask.Aegis, e.ToString());
            }
        }
예제 #6
0
        public async Task Start(IPAddress address = null, int bindPort = 9050)
        {
            if (_alive)
            {
                throw new Exception("Cannot start, server is running");
            }

            if (address == null)
            {
                address = await Utils.GetIPAddress().ConfigureAwait(false);
            }

            _listener = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp)
            {
                NoDelay = true
            };
            _listener.Bind(new IPEndPoint(address, bindPort));
            _listener.Listen(100);

            _alive = true;

            HostName = address.ToString();

            Socket socket;

            try
            {
                while (true)
                {
                    socket = await _listener.AcceptAsync().ConfigureAwait(false);

                    socket.NoDelay = true;
                    _ = ProcessSocket(socket);
                }
            }
            catch { }

            ShutDown();
        }
예제 #7
0
        public async void Start()
        {
            var listener      = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            var localEndPoint = new IPEndPoint(IPAddress.Any, _port);

            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(100);

                while (true)
                {
                    var clientSocket = await listener.AcceptAsync();

                    ProcessSocket(clientSocket);
                }
            }
            catch (Exception e)
            {
                Logger.Write(e);
            }
        }
예제 #8
0
        protected override void Start(CancellationToken token)
        {
            var listener    = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            var connectArgs = new SocketAsyncEventArgs();

            token.Register(() => {
                listener.Close();
                connectArgs.Dispose();
            });

            listener.Bind(OriginalEndPoint);
            EndPoint = (IPEndPoint)listener.LocalEndPoint;

            listener.Listen(6);

            connectArgs.Completed += OnSocketReceived;

            if (!listener.AcceptAsync(connectArgs))
            {
                OnSocketReceived(listener, connectArgs);
            }
        }
예제 #9
0
        private void ContinueAccept(SocketAsyncEventArgs currentAcceptor)
        {
            bool callbackPending;

            try
            {
                callbackPending = socket.AcceptAsync(currentAcceptor);
            }
            catch (ObjectDisposedException)
            {
                // either acceptor is disposed/corrupted, or socket is closed
                StartAccept(); // possible stack overflow if too many accepts end up bad

                HandleBadAcceptor(currentAcceptor);
                return;
            }

            if (!callbackPending)
            {
                ProcessAccept(currentAcceptor);
            }
        }
예제 #10
0
        /// <summary>
        /// 开始客户端连接监听
        /// </summary>
        public void StartAccept(SocketAsyncEventArgs e)
        {
            //如果当前传入为空  说明调用新的客户端连接监听事件 否则的话 移除当前客户端连接
            if (e == null)
            {
                e            = new SocketAsyncEventArgs();
                e.Completed += new EventHandler <SocketAsyncEventArgs>(Accept_Comleted);
            }
            else
            {
                e.AcceptSocket = null;
            }
            //信号量-1
            acceptClients.WaitOne();
            bool result = server.AcceptAsync(e);

            //判断异步事件是否挂起  没挂起说明立刻执行完成  直接处理事件 否则会在处理完成后触发Accept_Comleted事件
            if (!result)
            {
                ProcessAccept(e);
            }
        }
예제 #11
0
        public EndPointListener(HttpListener listener, IPAddress addr, int port, bool secure)
        {
            this.listener = listener;

            if (secure)
            {
                this.secure = secure;
                cert        = listener.LoadCertificateAndKey(addr, port);
            }

            endpoint = new IPEndPoint(addr, port);
            sock     = new Socket(addr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            sock.Bind(endpoint);
            sock.Listen(500);
            SocketAsyncEventArgs args = new SocketAsyncEventArgs();

            args.UserToken  = this;
            args.Completed += OnAccept;
            sock.AcceptAsync(args);
            prefixes     = new Hashtable();
            unregistered = new Dictionary <HttpConnection, HttpConnection> ();
        }
예제 #12
0
        public void CreateSocketServer()
        {
            s_listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
            s_listener.Listen(int.MaxValue);
            var ep = (IPEndPoint)s_listener.LocalEndPoint;

            s_uri = new Uri($"https://{ep.Address}:{ep.Port}/");

            Task.Run(async() =>
            {
                while (true)
                {
                    Socket s    = await s_listener.AcceptAsync();
                    var ignored = Task.Run(async() =>
                    {
                        using (X509Certificate2 serverCert = GetServerCertificate())
                            using (var serverStream = new SslStream(new NetworkStream(s, true), false, delegate { return(true); }))
                            {
                                await serverStream.AuthenticateAsServerAsync(serverCert, false, SslProtocols.None, false);
                                using (var reader = new StreamReader(serverStream))
                                    using (var writer = new StreamWriter(serverStream)
                                    {
                                        AutoFlush = true
                                    })
                                    {
                                        while (true)
                                        {
                                            while (!string.IsNullOrEmpty(await reader.ReadLineAsync()))
                                            {
                                                ;
                                            }
                                            await writer.WriteAsync("HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello");
                                        }
                                    }
                            }
                    });
                }
            });
        }
예제 #13
0
 /// <summary>
 /// Binds and listens for connections on the specified port.
 /// </summary>
 /// <param name="address"></param>
 /// <param name="port"></param>
 /// <returns></returns>
 private Socket BindSocket(IPAddress address, int port)
 {
     try {
         var endpoint = new IPEndPoint(address, port);
         var socket   = new Socket(endpoint.AddressFamily,
                                   SocketType.Stream, ProtocolType.Tcp);
         var args = new SocketAsyncEventArgs();
         args.Completed += OnAccept;
         args.UserToken  = socket;
         socket.Bind(endpoint);
         socket.Listen(int.MaxValue);
         if (!socket.AcceptAsync(args))
         {
             OnAccept(null, args);
         }
         return(socket);
     }
     catch (Exception ex) {
         _logger.Warning(ex, "failed to create listening socket.");
         return(null);
     }
 }
예제 #14
0
        private async Task AcceptClientConnectionsAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
#if NET452 || NET461
                    var clientSocket = await Task.Factory.FromAsync(_socket.BeginAccept, _socket.EndAccept, null).ConfigureAwait(false);
#else
                    var clientSocket = await _socket.AcceptAsync().ConfigureAwait(false);
#endif
#pragma warning disable 4014
                    Task.Run(() => TryHandleClientConnectionAsync(clientSocket), cancellationToken);
#pragma warning restore 4014
                }
                catch (Exception exception)
                {
                    _logger.Error(exception, $"Error while accepting connection at TCP listener {_socket.LocalEndPoint} TLS={_tlsCertificate != null}.");
                    await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false);
                }
            }
        }
예제 #15
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            // Setup Netowrk Socket
            Server = new Socket(SocketType.Stream, ProtocolType.Tcp);
            Server.Bind(new IPEndPoint(IPAddress.Any, 1911));
            Server.Listen(100);

            // Setup Servos
            var controller = GpioController.GetDefault();

            // GPIO 18
            var pin = controller.OpenPin(18, GpioSharingMode.Exclusive);

            pin.SetDriveMode(GpioPinDriveMode.Output);
            Azimuth = new ServoController(new SofwarePwm(n => pin.Write(n ? GpioPinValue.High : GpioPinValue.Low), 50, 0));
            Azimuth.Start(90);

            // GPIO 23
            pin = controller.OpenPin(23, GpioSharingMode.Exclusive);
            pin.SetDriveMode(GpioPinDriveMode.Output);
            Inclenation = new ServoController(new SofwarePwm(n => pin.Write(n ? GpioPinValue.High : GpioPinValue.Low), 50, 0));
            Inclenation.Start(90);

            Server.Listen(10);
            var connectEvent = new AutoResetEvent(false);

            while (true)
            {
                SocketAsyncEventArgs e = new SocketAsyncEventArgs();
                e.Completed += AcceptCallback;
                if (!Server.AcceptAsync(e))
                {
                    AcceptCallback(Server, e);
                    connectEvent.Set();
                }

                connectEvent.WaitOne(1000);
            }
        }
예제 #16
0
        public async void AcceptConnections()
        {
            while (true)
            {
                Socket clientSocket = null;
                try
                {
                    try
                    {
                        clientSocket = await _serverSocket.AcceptAsync();
                    }
                    catch (ObjectDisposedException)
                    {
                        break;
                    }

                    var client = await Transport.AcceptAsync(clientSocket,
                                                             supportsFdPassing : _serverSocket.AddressFamily == AddressFamily.Unix);

                    lock (_gate)
                    {
                        if (IsDisposed)
                        {
                            client.Dispose();
                            break;
                        }
                        var clientsUpdated = new IMessageStream[_clients.Length + 1];
                        Array.Copy(_clients, clientsUpdated, _clients.Length);
                        clientsUpdated[clientsUpdated.Length - 1] = client;
                        _clients = clientsUpdated;
                    }
                    _connection.ReceiveMessages(client, RemoveStream);
                }
                catch
                {
                    clientSocket?.Dispose();
                }
            }
        }
예제 #17
0
        public void Start()
        {
            Debug.Info("Socket server starting");

            Debug.Info($"Port: {Settings.Server.SrvPort}");

            Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            /// listenSocket.Bind(new IPEndPoint(IPAddress.Loopback, 4444));
            listenSocket.Bind(new IPEndPoint(IPAddress.Any, Convert.ToInt16(Settings.Server.SrvPort)));
            listenSocket.Listen(100);
            SocketAsyncEventArgs e = new SocketAsyncEventArgs();

            e.Completed += AcceptCallback;
            if (!listenSocket.AcceptAsync(e))
            {
                AcceptCallback(listenSocket, e);
            }
            Console.WriteLine("Socket server Ending");

            // Console.ReadKey(true);
        }
예제 #18
0
        public override void Initialize()
        {
            if (_socket != null)
            {
                return;
            }

            _policy = Encoding.UTF8.GetBytes(string.Format(PolicyTemplate, PortFrom, PortTo));

            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            {
                ExclusiveAddressUse = true
            };
            _socket.Bind(new IPEndPoint(IPAddress.Any, 943));
            _socket.Listen(100);

            var args = new SocketAsyncEventArgs();

            args.Completed += AcceptAsyncCompleted;

            _socket.AcceptAsync(args);
        }
예제 #19
0
        /// <summary>
        /// 开始接受连接请求
        /// </summary>
        /// <param name="acceptEventArg"></param>
        private void StartAccept(SocketAsyncEventArgs acceptEventArg)
        {
            if (acceptEventArg == null)
            {
                acceptEventArg            = new SocketAsyncEventArgs();
                acceptEventArg.Completed += new EventHandler <SocketAsyncEventArgs>(AcceptEventArg_Completed);
            }
            else
            {
                // 由于上下文对象正在被使用Socket必须被清理
                acceptEventArg.AcceptSocket = null;
            }
            try
            {
                m_maxNumberAcceptedClients.WaitOne();// 对信号量进行一次P操作

                bool willRaiseEvent = listenSocket.AcceptAsync(acceptEventArg);
                if (!willRaiseEvent)
                {
                    ProcessAccept(acceptEventArg);
                }
            }
            catch (ObjectDisposedException)
            {
            }
            catch (SocketException socketException)
            {
                RaiseErrorEvent(null, new AsyncSocketException("服务器接受客户端请求发生一次异常", socketException));

                // 接受客户端发生异常
                //throw new AsyncSocketException("服务器接受客户端请求发生一次异常", AsyncSocketErrorCode.ServerAcceptFailure);
            }
            catch (Exception exception_debug)
            {
                Debug.WriteLine("调试:" + exception_debug.Message);
                throw exception_debug;
            }
        }
예제 #20
0
    public void Listen(ushort port)
    {
        try
        {
            if (!_Listening)
            {
                _Clients = new List <ServerClient>();

                Item                      = new SocketAsyncEventArgs();
                Item.Completed           += Process;
                Item.AcceptSocket         = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                Item.AcceptSocket.NoDelay = true;

                if (_KeepAlive)
                {
                    Item.AcceptSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 20000);
                }

                Handle = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                Handle.Bind(new IPEndPoint(IPAddress.Any, port));
                Handle.Listen(10);

                Processing = false;
                _Listening = true;

                OnStateChanged(true);
                if (!Handle.AcceptAsync(Item))
                {
                    Process(null, Item);
                }
            }
        }
        catch (Exception ex)
        {
            OnExceptionThrown(ex);
            Disconnect();
        }
    }
예제 #21
0
        private void ProcessAccept(SocketAsyncEventArgs e)
        {
            bool bLoop = false;

            do
            {
                Socket socket = null;
                try
                {
                    if (e.SocketError != SocketError.Success)
                    {
                        var errorCode = (int)e.SocketError;
                        if (errorCode == 995 || errorCode == 10004 || errorCode == 10038)
                        {
                            return;
                        }
                    }
                    socket = e.AcceptSocket;
                    if (socket != null)
                    {
                        OnNewSocket(socket);
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.LogException(ex);
                    if (socket != null)
                    {
                        socket.Close();
                    }
                }
                finally
                {
                    _AcceptEvent.AcceptSocket = null;
                    bLoop = !_LocalSocket.AcceptAsync(_AcceptEvent);
                }
            } while (bLoop);
        }
예제 #22
0
        public async Task Handle()
        {
            //var document = new Documents();
            //var keys = document.GetKeys();
            //var api = new TwitterApi(keys);
            //var sentences = api.GiveMeMostRecentTweets("Pontifex_ln");
            //var tweets = new List<TweetInDatabase>();
            //foreach (var sentence in sentences)
            //{
            //    var tweet = new TweetInDatabase() { Text = sentence.CleanTweet() };
            //    tweets.Add(tweet);
            //}
            //document.StoreSermonTweetFragments(tweets, "ln");
            //var epis = new Epistula() { Preparatio = 20, Lingua = "ln", Modus = "pontifex" };
            //var proc = new Sermon();
            //Console.WriteLine(proc.Generate(epis));

            System.Console.WriteLine($"Starting TCP Server on port {Port}");
            Accepting = true;
            _socket.Listen(100);
            //handle new connection
            //check for disconnects
            //check for new requests
            //send back messages
            while (Accepting)
            {
                var acceptTask = _socket.AcceptAsync();
                foreach (var conn in _clients)
                {
                    ProcessConnectionAsync(conn);
                }
                var client = await acceptTask;
                _clients.Add(client);
            }
            //accept
            //invoke connecteD?
            //receive messages?
        }
예제 #23
0
        public void Listen(ushort port)
        {
            try
            {
                if (!Listening)
                {
                    _keepAlives = new List <KeepAlive>();

                    _clients = new List <Client>();

                    _item            = new SocketAsyncEventArgs();
                    _item.Completed += Process;

                    _handle = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    _handle.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
                    _handle.NoDelay = true;

                    _handle.Bind(new IPEndPoint(IPAddress.Any, port));
                    _handle.Listen(10);

                    Processing = false;
                    Listening  = true;

                    OnServerState(true);

                    SendKeepAlives();

                    if (!_handle.AcceptAsync(_item))
                    {
                        Process(null, _item);
                    }
                }
            }
            catch
            {
                Disconnect();
            }
        }
예제 #24
0
        private async Task AcceptCallback(Socket listener)
        {
            List <Task> pending_tasks = new List <Task>();

            while (true)
            {
                try
                {
                    pending_tasks.Add(listener.AcceptAsync());
                    Task task = await Task.WhenAny(pending_tasks);

                    pending_tasks.Remove(task);

                    if (task is Task <Socket> )
                    {
                        Socket client = await(Task <Socket>) task;
                        if (ClientConnected != null)
                        {
                            pending_tasks.Add(SetupClient(client));
                        }
                        else
                        {
                            // There was noone to accept the message, so just close
                            client.Dispose();
                        }
                    }
                }
                catch (ObjectDisposedException)
                {
                    // If client socket closed then exit loop.
                    break;
                }
                catch (Exception ex)
                {
                    _logger.LogException(ex);
                }
            }
        }
예제 #25
0
        public bool Start(int backLog = 10)
        {
            if (IsRuning)
            {
                return(false);
            }
            try
            {
                IPEndPoint localEndPoint = new IPEndPoint(Address, Port);
                Socket = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                if (localEndPoint.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    Socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);
                    Socket.Bind(new IPEndPoint(IPAddress.IPv6Any, localEndPoint.Port));
                }
                else
                {
                    Socket.Bind(localEndPoint);
                }
                Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
                Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);

                Socket.Listen(backLog);

                Msaea            = new SocketAsyncEventArgs();
                Msaea.Completed += new EventHandler <SocketAsyncEventArgs>(Msaea_Completed);
                IsRuning         = true;
                if (!Socket.AcceptAsync(Msaea))
                {
                    ProcessAccept(Msaea);
                }
                return(true);
            }
            catch
            {
                return(false);
            }
        }
예제 #26
0
        public void AcceptAsync_IPv6_Success()
        {
            Assert.True(Capability.IPv6Support());

            AutoResetEvent completed       = new AutoResetEvent(false);
            AutoResetEvent completedClient = new AutoResetEvent(false);

            using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
            {
                int port = sock.BindToAnonymousPort(IPAddress.IPv6Loopback);
                sock.Listen(1);

                SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                args.Completed += OnAcceptCompleted;
                args.UserToken  = completed;

                Assert.True(sock.AcceptAsync(args));
                _log.WriteLine("IPv6 Server: Waiting for clients.");

                using (Socket client = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
                {
                    SocketAsyncEventArgs argsClient = new SocketAsyncEventArgs();
                    argsClient.RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, port);
                    argsClient.Completed     += OnConnectCompleted;
                    argsClient.UserToken      = completedClient;
                    client.ConnectAsync(argsClient);

                    _log.WriteLine("IPv6 Client: Connecting.");
                    Assert.True(completed.WaitOne(5000), "IPv6: Timed out while waiting for connection");

                    Assert.Equal <SocketError>(SocketError.Success, args.SocketError);
                    Assert.NotNull(args.AcceptSocket);
                    Assert.True(args.AcceptSocket.Connected, "IPv6 Accept Socket was not connected");
                    Assert.NotNull(args.AcceptSocket.RemoteEndPoint);
                    Assert.Equal(client.LocalEndPoint, args.AcceptSocket.RemoteEndPoint);
                }
            }
        }
예제 #27
0
        private async Task AcceptClientConnectionsAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
#if NET452 || NET461
                    var clientSocket = await Task.Factory.FromAsync(_socket.BeginAccept, _socket.EndAccept, null).ConfigureAwait(false);
#else
                    var clientSocket = await _socket.AcceptAsync().ConfigureAwait(false);
#endif

                    if (clientSocket == null)
                    {
                        continue;
                    }

                    Task.Run(() => TryHandleClientConnectionAsync(clientSocket), cancellationToken).Forget(_logger);
                }
                catch (OperationCanceledException)
                {
                }
                catch (Exception exception)
                {
                    if (exception is SocketException socketException)
                    {
                        if (socketException.SocketErrorCode == SocketError.ConnectionAborted ||
                            socketException.SocketErrorCode == SocketError.OperationAborted)
                        {
                            continue;
                        }
                    }

                    _logger.Error(exception, $"Error while accepting connection at TCP listener {_localEndPoint} TLS={_tlsCertificate != null}.");
                    await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false);
                }
            }
        }
예제 #28
0
        public void AcceptAsync_IpV4_Success()
        {
            Assert.True(Capability.IPv4Support());

            AutoResetEvent completed = new AutoResetEvent(false);
            AutoResetEvent completedClient = new AutoResetEvent(false);

            using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                int port = sock.BindToAnonymousPort(IPAddress.Loopback);
                sock.Listen(1);

                SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                args.Completed += OnAcceptCompleted;
                args.UserToken = completed;

                Assert.True(sock.AcceptAsync(args));
                _log.WriteLine("IPv4 Server: Waiting for clients.");

                using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    SocketAsyncEventArgs argsClient = new SocketAsyncEventArgs();
                    argsClient.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, port);
                    argsClient.Completed += OnConnectCompleted;
                    argsClient.UserToken = completedClient;
                    client.ConnectAsync(argsClient);

                    _log.WriteLine("IPv4 Client: Connecting.");
                    Assert.True(completed.WaitOne(5000), "IPv4: Timed out while waiting for connection");

                    Assert.Equal<SocketError>(SocketError.Success, args.SocketError);
                    Assert.NotNull(args.AcceptSocket);
                    Assert.True(args.AcceptSocket.Connected, "IPv4 Accept Socket was not connected");
                    Assert.NotNull(args.AcceptSocket.RemoteEndPoint);
                    Assert.Equal(client.LocalEndPoint, args.AcceptSocket.RemoteEndPoint);
                }
            }
        }
예제 #29
0
        public static Task <Socket> AcceptSocketAsync(this Socket socket)
        {
            var acceptSource = new TaskCompletionSource <Socket>();

            void AcceptHandler(object sender, SocketAsyncEventArgs eventArgs)
            {
                var error = eventArgs.SocketError;

                eventArgs.Completed -= AcceptHandler;
                eventArgs.Dispose();

                if (error != SocketError.Success)
                {
                    acceptSource.TrySetException(new SocketException((int)error));
                    return;
                }

                acceptSource.TrySetResult(eventArgs.AcceptSocket);
            }

            var e = new SocketAsyncEventArgs();

            e.Completed += AcceptHandler;

            try
            {
                if (!socket.AcceptAsync(e))
                {
                    AcceptHandler(null, e);
                }
            }
            catch (Exception ex)
            {
                acceptSource.TrySetException(ex);
            }

            return(acceptSource.Task);
        }
예제 #30
0
 private void StartAccept(SocketAsyncEventArgs AcceptEventArgs)
 {
     try
     {
         if (IsListening)
         {
             if (AcceptEventArgs == null)
             {
                 AcceptEventArgs            = new SocketAsyncEventArgs();
                 AcceptEventArgs.Completed += AcceptEventArgs_Completed;
             }
             else
             {
                 AcceptEventArgs.AcceptSocket = null;
             }
             if (!Listener.AcceptAsync(AcceptEventArgs))
             {
                 ProcessAccept(AcceptEventArgs);
             }
         }
     }
     catch (SocketException)
     {
         if (IsListening == true && IsShutdown == false)
         {
             SetOnException(new Exception("Server Exception (StartAccept): Could not start accept due to server shutdown"));
             Shutdown();
         }
     }
     catch (Exception ex)
     {
         if (IsListening == true && IsShutdown == false)
         {
             SetOnException(new Exception(string.Format("Server Exception (StartAccept): {0}", ex.Message)));
             Shutdown();
         }
     }
 }
예제 #31
0
        /// <summary>
        /// Starts accepting incoming clients.
        /// </summary>
        /// <param name="args">The async event args to use, if any (passing null
        /// will create a new object).</param>
        private void Accept(SocketAsyncEventArgs args)
        {
            if (args == null)
            {
                args            = SocketAsyncEventArgsPool.Acquire();
                args.Completed += OnAccept;
            }
            else
            {
                args.AcceptSocket = null;
            }

            try
            {
                if (!_socket.AcceptAsync(args))
                {
                    OnAccept(this, args);
                }
            }
            catch (Exception ex)
            {
                args.Completed -= OnAccept;
                SocketAsyncEventArgsPool.Release(args);

                if (ex is ObjectDisposedException)
                {
                    return;
                }

                if (ex is SocketException)
                {
                    ExceptionManager.RegisterException(ex);
                    return;
                }

                throw;
            }
        }
예제 #32
0
        /// <summary>
        /// Discover the server EndPoint. Will async wait forever if it cannot find one.
        /// </summary>
        /// <param name="port"></param>
        /// <returns>IPEndPoint of the server</returns>
        private static async Task <IPEndPoint> DiscoverServerEndPoint(int port)
        {
            // Create our broadcast address
            var broadcastIp       = IPAddress.Parse("255.255.255.255");
            var broadcastEndpoint = new IPEndPoint(broadcastIp, port);

            // Create a UDP socket with broadcasting enabled
            var broadcaster = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            broadcaster.EnableBroadcast = true;

            // Connect to this socket to find our local IP
            broadcaster.Connect(broadcastEndpoint);
            var localIp = ((IPEndPoint)broadcaster.LocalEndPoint).Address;

            // Create a TCP socket for listening for the server IP
            var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // Bind to our local IP we just discovered but with our standard port
            listener.Bind(new IPEndPoint(localIp, port));
            listener.Listen(120);

            // Send off our broadcast datagram
            broadcaster.SendTo(Array.Empty <byte>(), broadcastEndpoint);

            // Async wait for the server IP address to come on the TCP socket
            var buffer = new byte[4];
            var socket = await listener.AcceptAsync();

            await socket.ReceiveAsync(buffer, SocketFlags.None);

            // Release all resources used by our sockets
            broadcaster.Dispose();
            listener.Dispose();

            // Return the address we received from the server
            return(new IPEndPoint(new IPAddress(buffer), port));
        }
예제 #33
0
        public async Task Socket_SendReceiveAsync_Success()
        {
            string path     = GetRandomNonExistingFilePath();
            var    endPoint = new UnixDomainSocketEndPoint(path);

            try
            {
                using (var server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
                    using (var client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
                    {
                        server.Bind(endPoint);
                        server.Listen(1);

                        await client.ConnectAsync(endPoint);

                        using (Socket accepted = await server.AcceptAsync())
                        {
                            var data = new byte[1];
                            for (int i = 0; i < 10; i++)
                            {
                                data[0] = (byte)i;

                                await accepted.SendAsync(new ArraySegment <byte>(data), SocketFlags.None);

                                data[0] = 0;

                                Assert.Equal(1, await client.ReceiveAsync(new ArraySegment <byte>(data), SocketFlags.None));
                                Assert.Equal(i, data[0]);
                            }
                        }
                    }
            }
            finally
            {
                try { File.Delete(path); }
                catch { }
            }
        }
예제 #34
0
 public void AcceptAsync_NotListening_Throws_InvalidOperation()
 {
     using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
     {
         socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
         Assert.Throws<InvalidOperationException>(() => socket.AcceptAsync(s_eventArgs));
     }
 }
예제 #35
0
        public void PollWrite_Single_Timeout()
        {
            using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                listener.BindToAnonymousPort(IPAddress.Loopback);
                listener.Listen(1);
                listener.AcceptAsync();

                Assert.False(listener.Poll(SelectTimeout, SelectMode.SelectWrite));
            }
        }
예제 #36
0
        public void SelectWrite_Multiple_Mixed()
        {
            using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            using (var sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                listener.BindToAnonymousPort(IPAddress.Loopback);
                listener.Listen(1);
                listener.AcceptAsync();

                var list = new List<Socket> { listener, sender };
                Socket.Select(null, list, null, SelectSuccessTimeoutMicroseconds);

                Assert.Equal(1, list.Count);
                Assert.Equal(sender, list[0]);
            }
        }
예제 #37
0
        public void SendRecvAsync_Stream_TCP(IPAddress listenAt, bool useMultipleBuffers)
        {
            const int BytesToSend = 123456;
            const int ListenBacklog = 1;
            const int LingerTime = 60;
            const int TestTimeout = 30000;

            var server = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            server.BindToAnonymousPort(listenAt);

            server.Listen(ListenBacklog);

            var serverFinished = new TaskCompletionSource<bool>();
            int bytesReceived = 0;
            var receivedChecksum = new Fletcher32();

            var serverEventArgs = new SocketAsyncEventArgs();
            server.AcceptAsync(serverEventArgs, remote =>
            {
                Action<int> recvHandler = null;
                bool first = true;

                if (!useMultipleBuffers)
                {
                    var recvBuffer = new byte[256];
                    recvHandler = received => 
                    {
                        if (!first)
                        {
                            if (received == 0)
                            {
                                remote.Dispose();
                                server.Dispose();
                                serverFinished.SetResult(true);
                                return;
                            }

                            bytesReceived += received;
                            receivedChecksum.Add(recvBuffer, 0, received);
                        }
                        else
                        {
                            first = false;
                        }

                        remote.ReceiveAsync(serverEventArgs, recvBuffer, 0, recvBuffer.Length, SocketFlags.None, recvHandler);
                    };
                }
                else
                {
                    var recvBuffers = new List<ArraySegment<byte>> {
                        new ArraySegment<byte>(new byte[123]),
                        new ArraySegment<byte>(new byte[256], 2, 100),
                        new ArraySegment<byte>(new byte[1], 0, 0),
                        new ArraySegment<byte>(new byte[64], 9, 33)
                    };

                    recvHandler = received =>
                    {
                        if (!first)
                        {
                            if (received == 0)
                            {
                                remote.Dispose();
                                server.Dispose();
                                serverFinished.SetResult(true);
                                return;
                            }

                            bytesReceived += received;
                            for (int i = 0, remaining = received; i < recvBuffers.Count && remaining > 0; i++)
                            {
                                ArraySegment<byte> buffer = recvBuffers[i];
                                int toAdd = Math.Min(buffer.Count, remaining);
                                receivedChecksum.Add(buffer.Array, buffer.Offset, toAdd);
                                remaining -= toAdd;
                            }
                        }
                        else
                        {
                            first = false;
                        }

                        remote.ReceiveAsync(serverEventArgs, recvBuffers, SocketFlags.None, recvHandler);
                    };
                }

                recvHandler(0);
            });

            EndPoint clientEndpoint = server.LocalEndPoint;
            var client = new Socket(clientEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            int bytesSent = 0;
            var sentChecksum = new Fletcher32();

            var clientEventArgs = new SocketAsyncEventArgs();
            client.ConnectAsync(clientEventArgs, clientEndpoint, () =>
            {
                Action<int> sendHandler = null;
                var random = new Random();
                var remaining = BytesToSend;
                bool first = true;

                if (!useMultipleBuffers)
                {
                    var sendBuffer = new byte[512];
                    sendHandler = sent =>
                    {
                        if (!first)
                        {
                            bytesSent += sent;
                            sentChecksum.Add(sendBuffer, 0, sent);

                            remaining -= sent;
                            Assert.True(remaining >= 0);
                            if (remaining == 0)
                            {
                                client.LingerState = new LingerOption(true, LingerTime);
                                client.Dispose();
                                return;
                            }
                        }
                        else
                        {
                            first = false;
                        }

                        random.NextBytes(sendBuffer);
                        client.SendAsync(clientEventArgs, sendBuffer, 0, Math.Min(sendBuffer.Length, remaining), SocketFlags.None, sendHandler);
                    };
                }
                else
                {
                    var sendBuffers = new List<ArraySegment<byte>> {
                        new ArraySegment<byte>(new byte[23]),
                        new ArraySegment<byte>(new byte[256], 2, 100),
                        new ArraySegment<byte>(new byte[1], 0, 0),
                        new ArraySegment<byte>(new byte[64], 9, 9)
                    };

                    sendHandler = sent =>
                    {
                        if (!first)
                        {
                            bytesSent += sent;
                            for (int i = 0, r = sent; i < sendBuffers.Count && r > 0; i++)
                            {
                                ArraySegment<byte> buffer = sendBuffers[i];
                                int toAdd = Math.Min(buffer.Count, r);
                                sentChecksum.Add(buffer.Array, buffer.Offset, toAdd);
                                r -= toAdd;
                            }

                            remaining -= sent;
                            if (remaining <= 0)
                            {
                                client.LingerState = new LingerOption(true, LingerTime);
                                client.Dispose();
                                return;
                            }
                        }
                        else
                        {
                            first = false;
                        }

                        for (int i = 0; i < sendBuffers.Count; i++)
                        {
                            random.NextBytes(sendBuffers[i].Array);
                        }

                        client.SendAsync(clientEventArgs, sendBuffers, SocketFlags.None, sendHandler);
                    };
                }

                sendHandler(0);
            });

            Assert.True(serverFinished.Task.Wait(TestTimeout), "Completed within allowed time");

            Assert.Equal(bytesSent, bytesReceived);
            Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum);
        }
예제 #38
0
        public static async Task SendRecvAsync_0ByteReceive_Success()
        {
            using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
                listener.Listen(1);

                Task<Socket> acceptTask = listener.AcceptAsync();
                await Task.WhenAll(
                    acceptTask, 
                    client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndPoint).Port)));

                using (Socket server = await acceptTask)
                {
                    TaskCompletionSource<bool> tcs = null;

                    var ea = new SocketAsyncEventArgs();
                    ea.SetBuffer(Array.Empty<byte>(), 0, 0);
                    ea.Completed += delegate { tcs.SetResult(true); };

                    for (int i = 0; i < 3; i++)
                    {
                        tcs = new TaskCompletionSource<bool>();

                        // Have the client do a 0-byte receive.  No data is available, so this should pend.
                        Assert.True(client.ReceiveAsync(ea));
                        Assert.Equal(0, client.Available);

                        // Have the server send 1 byte to the client.
                        Assert.Equal(1, server.Send(new byte[1], 0, 1, SocketFlags.None));

                        // The client should now wake up, getting 0 bytes with 1 byte available.
                        await tcs.Task;
                        Assert.Equal(0, ea.BytesTransferred);
                        Assert.Equal(SocketError.Success, ea.SocketError);
                        Assert.Equal(1, client.Available); // Due to #13778, this sometimes fails on macOS

                        // Receive that byte
                        Assert.Equal(1, client.Receive(new byte[1]));
                        Assert.Equal(0, client.Available);
                    }
                }
            }
        }
예제 #39
0
        public void AcceptAsync_WithReceiveBuffer_Success()
        {
            Assert.True(Capability.IPv4Support());

            AutoResetEvent accepted = new AutoResetEvent(false);

            using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                int port = server.BindToAnonymousPort(IPAddress.Loopback);
                server.Listen(1);

                const int acceptBufferOverheadSize = 288; // see https://msdn.microsoft.com/en-us/library/system.net.sockets.socket.acceptasync(v=vs.110).aspx
                const int acceptBufferDataSize = 256;
                const int acceptBufferSize = acceptBufferOverheadSize + acceptBufferDataSize;

                byte[] sendBuffer = new byte[acceptBufferDataSize];
                new Random().NextBytes(sendBuffer);

                SocketAsyncEventArgs acceptArgs = new SocketAsyncEventArgs();
                acceptArgs.Completed += OnAcceptCompleted;
                acceptArgs.UserToken = accepted;
                acceptArgs.SetBuffer(new byte[acceptBufferSize], 0, acceptBufferSize);

                Assert.True(server.AcceptAsync(acceptArgs));
                _log.WriteLine("IPv4 Server: Waiting for clients.");

                using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    client.Connect(IPAddress.Loopback, port);
                    client.Send(sendBuffer);
                    client.Shutdown(SocketShutdown.Both);
                }

                Assert.True(
                    accepted.WaitOne(Configuration.PassingTestTimeout), "Test completed in alotted time");

                Assert.Equal(
                    SocketError.Success, acceptArgs.SocketError);

                Assert.Equal(
                    acceptBufferDataSize, acceptArgs.BytesTransferred);

                Assert.Equal(
                    new ArraySegment<byte>(sendBuffer), 
                    new ArraySegment<byte>(acceptArgs.Buffer, 0, acceptArgs.BytesTransferred));
            }
        }
예제 #40
0
        public void ConcurrentSendReceive()
        {
            using (Socket server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
            using (Socket client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
            {
                const int Iters = 2048;
                byte[] sendData = new byte[Iters];
                byte[] receiveData = new byte[sendData.Length];
                new Random().NextBytes(sendData);

                string path = GetRandomNonExistingFilePath();

                server.Bind(new UnixDomainSocketEndPoint(path));
                server.Listen(1);

                Task<Socket> acceptTask = server.AcceptAsync();
                client.Connect(new UnixDomainSocketEndPoint(path));
                acceptTask.Wait();
                Socket accepted = acceptTask.Result;

                Task[] writes = new Task[Iters];
                Task<int>[] reads = new Task<int>[Iters];
                for (int i = 0; i < Iters; i++)
                {
                    writes[i] = client.SendAsync(new ArraySegment<byte>(sendData, i, 1), SocketFlags.None);
                }
                for (int i = 0; i < Iters; i++)
                {
                    reads[i] = accepted.ReceiveAsync(new ArraySegment<byte>(receiveData, i, 1), SocketFlags.None);
                }
                Task.WaitAll(writes);
                Task.WaitAll(reads);

                Assert.Equal(sendData, receiveData);
            }
        }
예제 #41
0
        public async Task Socket_SendReceiveAsync_Success()
        {
            string path = GetRandomNonExistingFilePath();
            var endPoint = new UnixDomainSocketEndPoint(path);
            try
            {
                using (var server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
                using (var client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
                {
                    server.Bind(endPoint);
                    server.Listen(1);

                    await client.ConnectAsync(endPoint);
                    using (Socket accepted = await server.AcceptAsync())
                    {
                        var data = new byte[1];
                        for (int i = 0; i < 10; i++)
                        {
                            data[0] = (byte)i;

                            await accepted.SendAsync(new ArraySegment<byte>(data), SocketFlags.None);
                            data[0] = 0;

                            Assert.Equal(1, await client.ReceiveAsync(new ArraySegment<byte>(data), SocketFlags.None));
                            Assert.Equal(i, data[0]);
                        }
                    }
                }
            }
            finally
            {
                try { File.Delete(path); }
                catch { }
            }
        }
예제 #42
0
        private void DualModeConnect_AcceptAsync_Helper(IPAddress listenOn, IPAddress connectTo)
        {
            using (Socket serverSocket = new Socket(SocketType.Stream, ProtocolType.Tcp))
            {
                int port = serverSocket.BindToAnonymousPort(listenOn);
                serverSocket.Listen(1);

                SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                args.Completed += AsyncCompleted;
                ManualResetEvent waitHandle = new ManualResetEvent(false);
                args.UserToken = waitHandle;

                _log.WriteLine(args.GetHashCode() + " SocketAsyncEventArgs with manual event " + waitHandle.GetHashCode());

                serverSocket.AcceptAsync(args);
                SocketClient client = new SocketClient(serverSocket, connectTo, port);
                Assert.True(waitHandle.WaitOne(Configuration.PassingTestTimeout), "Timed out while waiting for connection");

                if (args.SocketError != SocketError.Success)
                {
                    throw new SocketException((int)args.SocketError);
                }

                Socket clientSocket = args.AcceptSocket;
                Assert.NotNull(clientSocket);
                Assert.True(clientSocket.Connected);
                Assert.True(clientSocket.DualMode);
                Assert.Equal(AddressFamily.InterNetworkV6, clientSocket.AddressFamily);
                Assert.Equal(connectTo.MapToIPv6(), ((IPEndPoint)clientSocket.LocalEndPoint).Address);
            }
        }
예제 #43
0
        public void AcceptAsync_WithReceiveBuffer_Failure()
        {
            //
            // Unix platforms don't yet support receiving data with AcceptAsync.
            //

            Assert.True(Capability.IPv4Support());

            using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                int port = server.BindToAnonymousPort(IPAddress.Loopback);
                server.Listen(1);

                SocketAsyncEventArgs acceptArgs = new SocketAsyncEventArgs();
                acceptArgs.Completed += OnAcceptCompleted;
                acceptArgs.UserToken = new ManualResetEvent(false);

                byte[] buffer = new byte[1024];
                acceptArgs.SetBuffer(buffer, 0, buffer.Length);

                Assert.Throws<PlatformNotSupportedException>(() => server.AcceptAsync(acceptArgs));
            }
        }
예제 #44
0
        public void Success()
        {
            AutoResetEvent completed = new AutoResetEvent(false);

            if (Socket.OSSupportsIPv4)
            {
                using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    int port = sock.BindToAnonymousPort(IPAddress.Loopback);
                    sock.Listen(1);

                    SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                    args.Completed += OnAcceptCompleted;
                    args.UserToken = completed;

                    // Not expecting the operation to finish synchronously as no client should be trying to connect.
                    Assert.True(sock.AcceptAsync(args));
                    _log.WriteLine("IPv4 Server: Waiting for clients.");

                    Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    client.Connect(new IPEndPoint(IPAddress.Loopback, port));

                    _log.WriteLine("IPv4 Client: Connecting.");
                    Assert.True(completed.WaitOne(Configuration.PassingTestTimeout), "IPv4: Timed out while waiting for connection");

                    Assert.Equal<SocketError>(SocketError.Success, args.SocketError);
                    Assert.NotNull(args.AcceptSocket);
                    Assert.True(args.AcceptSocket.Connected, "IPv4 Accept Socket was not connected");

                    client.Dispose();
                }
            }

            if (Socket.OSSupportsIPv6)
            {
                using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
                {
                    int port = sock.BindToAnonymousPort(IPAddress.IPv6Loopback);
                    sock.Listen(1);

                    SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                    args.Completed += OnAcceptCompleted;
                    args.UserToken = completed;

                    Assert.True(sock.AcceptAsync(args));
                    _log.WriteLine("IPv6 Server: Waiting for clients.");

                    Socket client = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
                    client.Connect(new IPEndPoint(IPAddress.IPv6Loopback, port));

                    _log.WriteLine("IPv6 Client: Connecting.");
                    Assert.True(completed.WaitOne(Configuration.PassingTestTimeout), "IPv6: Timed out while waiting for connection");

                    Assert.Equal<SocketError>(SocketError.Success, args.SocketError);
                    Assert.NotNull(args.AcceptSocket);
                    Assert.True(args.AcceptSocket.Connected, "IPv6 Accept Socket was not connected");
                    //Assert.NotNull(args.AcceptSocket.m_RightEndPoint, "m_RightEndPoint was not set");
                    //Assert.Equal(client.LocalEndPoint, args.AcceptSocket.m_RemoteEndPoint, "m_RemoteEndPoint is wrong!");

                    client.Dispose();
                }
            }
        }
예제 #45
0
        public async Task Socket_Connect_IPv4AddressAsStringHost_Supported()
        {
            using (Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                host.Bind(new IPEndPoint(IPAddress.Loopback, 0));
                host.Listen(1);
                Task accept = host.AcceptAsync();

                using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    s.Connect(IPAddress.Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port);
                }

                await accept;
            }
        }
예제 #46
0
        public void SelectWrite_Multiple_Timeout()
        {
            using (var firstListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            using (var secondListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                firstListener.BindToAnonymousPort(IPAddress.Loopback);
                firstListener.Listen(1);
                firstListener.AcceptAsync();
                
                secondListener.BindToAnonymousPort(IPAddress.Loopback);
                secondListener.Listen(1);
                secondListener.AcceptAsync();

                var list = new List<Socket> { firstListener, secondListener };
                Socket.Select(null, list, null, SelectTimeout);

                Assert.Equal(0, list.Count);
            }
        }
예제 #47
0
        private static KeyValuePair<Socket, Socket> CreateConnectedSockets()
        {
            using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                listener.LingerState = new LingerOption(true, 0);
                listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
                listener.Listen(1);

                Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                client.LingerState = new LingerOption(true, 0);

                Task<Socket> acceptTask = listener.AcceptAsync();
                client.Connect(listener.LocalEndPoint);
                Socket server = acceptTask.GetAwaiter().GetResult();

                return new KeyValuePair<Socket, Socket>(client, server);
            }
        }
예제 #48
0
        private void DualModeConnect_AcceptAsync_Helper(IPAddress listenOn, IPAddress connectTo)
        {
            using (Socket serverSocket = new Socket(SocketType.Stream, ProtocolType.Tcp))
            {
                int port = serverSocket.BindToAnonymousPort(listenOn);
                serverSocket.Listen(1);

                SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                args.Completed += AsyncCompleted;
                ManualResetEvent waitHandle = new ManualResetEvent(false);
                args.UserToken = waitHandle;
                args.SocketError = SocketError.SocketError;

                _log.WriteLine(args.GetHashCode() + " SocketAsyncEventArgs with manual event " + waitHandle.GetHashCode());
                if (!serverSocket.AcceptAsync(args))
                {
                    throw new SocketException((int)args.SocketError);
                }

                SocketClient client = new SocketClient(_log, serverSocket, connectTo, port);

                var waitHandles = new WaitHandle[2];
                waitHandles[0] = waitHandle;
                waitHandles[1] = client.WaitHandle;

                int completedHandle = WaitHandle.WaitAny(waitHandles, Configuration.PassingTestTimeout);

                if (completedHandle == WaitHandle.WaitTimeout)
                {
                    throw new TimeoutException("Timed out while waiting for either of client and server connections...");
                }

                if (completedHandle == 1)   // Client finished
                {
                    if (client.Error != SocketError.Success)
                    {
                        // Client SocketException
                        throw new SocketException((int)client.Error);
                    }

                    if (!waitHandle.WaitOne(5000))  // Now wait for the server.
                    {
                        throw new TimeoutException("Timed out while waiting for the server accept...");
                    }
                }

                _log.WriteLine(args.SocketError.ToString());


                if (args.SocketError != SocketError.Success)
                {
                    throw new SocketException((int)args.SocketError);
                }

                Socket clientSocket = args.AcceptSocket;
                Assert.NotNull(clientSocket);
                Assert.True(clientSocket.Connected);
                AssertDualModeEnabled(clientSocket, listenOn);
                Assert.Equal(AddressFamily.InterNetworkV6, clientSocket.AddressFamily);
                if (connectTo == IPAddress.Loopback)
                {
                    Assert.Contains(((IPEndPoint)clientSocket.LocalEndPoint).Address, ValidIPv6Loopbacks);
                }
                else
                {
                    Assert.Equal(connectTo.MapToIPv6(), ((IPEndPoint)clientSocket.LocalEndPoint).Address);
                }
                clientSocket.Dispose();
            }
        }
예제 #49
0
        public async Task Socket_ConnectAsync_IPv6AddressAsStringHost_Supported()
        {
            using (Socket host = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
            {
                host.Bind(new IPEndPoint(IPAddress.IPv6Loopback, 0));
                host.Listen(1);

                using (Socket s = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
                {
                    await Task.WhenAll(
                        host.AcceptAsync(),
                        s.ConnectAsync(IPAddress.IPv6Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port));
                }
            }
        }