AcceptAsync() public method

public AcceptAsync ( SocketAsyncEventArgs e ) : bool
e SocketAsyncEventArgs
return bool
Exemplo n.º 1
0
        /// <summary>
        /// 루프를 돌며 클라이언트를 받아 들이고
        /// 하나의 접속 처리가 완료된 후 다음 accept를 수행하기 위해서 event객체를 통해 흐름을 제어함.
        /// </summary>
        private void DoListen()
        {
            _flowControlEvent = new AutoResetEvent(false);

            while (true)
            {
                // SocketAsyncEventArgs를 재사용 하기 위해서 null로 만들어 준다.
                _acceptArgs.AcceptSocket = null;

                bool pending = true;
                try
                {
                    // 비동기 accept를 호출하여 클라이언트의 접속을 받아들입니다.
                    // 비동기 매소드 이지만 동기적으로 수행이 완료될 경우도 있으니
                    // 리턴값을 확인하여 분기시켜야 합니다.
                    pending = _listenSocket.AcceptAsync(_acceptArgs);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    continue;
                }

                // 즉시 완료 되면 이벤트가 발생하지 않으므로 리턴값이 false일 경우 콜백 매소드를 직접 호출해 줍니다.
                // pending상태라면 비동기 요청이 들어간 상태이므로 콜백 매소드를 기다리면 됩니다.
                if (pending == false)
                {
                    OnAcceptCompleted(null, _acceptArgs);
                }

                // 클라이언트 접속 처리가 완료되면 이벤트 객체의 신호를 전달받아 다시 루프를 수행하도록 합니다.
                _flowControlEvent.WaitOne();
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Helper, assign the pending async accept args.
        /// </summary>
        SocketAsyncEventArgs AssignAsyncAcceptArgs()
        {
            System.Net.Sockets.Socket listenSocket = _listenSocket;
            if (listenSocket == null)
            {
                return(null);
            }

            SocketAsyncEventArgs e = new SocketAsyncEventArgs();

            e.Completed += new EventHandler <SocketAsyncEventArgs>(SocketAsyncEventArgs_Completed);

            if (listenSocket.AcceptAsync(e) == false)
            {
                if (e.SocketError == SocketError.Success)
                {
                    SocketAsyncEventArgs_Completed(this, e);
                }
                else
                {// Accept failed.
#if Matrix_Diagnostics
                    Monitor.Fatal("Async accept failed.");
#endif
                }
            }

            return(e);
        }
        private void Initialize(IPEndPoint endpoint, Action<TcpStreamChannel> onClientAccepted)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException("endpoint");
            }
            if (onClientAccepted == null)
            {
                throw new ArgumentNullException("onClientConnected");
            }

            _onClientAcceptedAction = onClientAccepted;
            _listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _listenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
            _listenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
            _listenSocket.Bind(endpoint);
            _listenSocket.Listen(10);

            _acceptEventArg = new SocketAsyncEventArgs();
            _acceptEventArg.Completed += OnAcceptNewClient;

            if (!_listenSocket.AcceptAsync(_acceptEventArg))
            {
                OnAcceptNewClient(null, _acceptEventArg);
            }
        }
        public EndPointListener(
			IPAddress address,
			int port,
			bool secure,
			string certFolderPath,
			X509Certificate2 defaultCert
		)
        {
            if (secure) {
                _secure = secure;
                _cert = getCertificate (port, certFolderPath, defaultCert);
                if (_cert == null)
                    throw new ArgumentException ("Server certificate not found.");
            }

            _endpoint = new IPEndPoint (address, port);
            _socket = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            _socket.Bind (_endpoint);
            _socket.Listen (500);
            var args = new SocketAsyncEventArgs ();
            args.UserToken = this;
            args.Completed += onAccept;
            _socket.AcceptAsync (args);
            _prefixes = new Dictionary<ListenerPrefix, HttpListener> ();
            _unregistered = new Dictionary<HttpConnection, HttpConnection> ();
        }
Exemplo n.º 5
0
        private void StartListening()
        {
            try
            {
                var listener = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                listener.Bind(_iPEndPoint);
                listener.Listen(200);
                _isStart = true;
                while (_isStart)
                {
                    _acceptEvent.AcceptSocket = null;
                    _allDone.Reset();
                    var pending = listener.AcceptAsync(_acceptEvent);

                    if (!pending)
                    {
                        Accept_Completed(null, _acceptEvent);
                    }
                    _allDone.WaitOne();
                }
            }
            catch (Exception.Exception ex)
            {
                throw ex;
            }
        }
        private void Listen(IPEndPoint localEndpoint)
        {
            _logger.Trace("Listen (sync) using local endpoint {0}", localEndpoint);

            // create a socket
            _listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // bind and listen
            try
            {
                _listener.Bind(localEndpoint);
                _listener.Listen(1);

                // accept the next connection
                bool completesAsynchronously = _listener.AcceptAsync(_socketOperation);

                if (!completesAsynchronously)
                {
                    SocketAsyncEventArgs_Completed(_socketOperation.AcceptSocket, _socketOperation);
                }
            }
            catch (Exception ex)
            {
                // raise error event
                var handlers = Error;
                if (handlers != null)
                {
                    var args = new NetworkErrorEventArgs("The listen operation failed: " + ex.ToString(), null, ex);
                    handlers(this, args);
                }
            }
        }
Exemplo n.º 7
0
        internal void Listen(String ipAddress, Int32 portNo)
        {
            try
            {
                if (_listenSocket != null)
                    throw new AegisException(AegisResult.AcceptorIsRunning, "Acceptor is already running.");


                if (ipAddress.Length == 0)
                    _listenEndPoint = new IPEndPoint(IPAddress.Any, portNo);
                else
                    _listenEndPoint = new IPEndPoint(IPAddress.Parse(ipAddress), portNo);


                _listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                _listenSocket.Bind(_listenEndPoint);
                _listenSocket.Listen(100);

                Logger.Write(LogType.Info, 1, "Listening on {0}, {1}", _listenEndPoint.Address, _listenEndPoint.Port);
                _listenSocket.AcceptAsync(_eventAccept);
            }
            catch (AegisException)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new AegisException(AegisResult.NetworkError, e, e.Message);
            }
        }
Exemplo n.º 8
0
        public void StartListening(int port)
        {
            Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, port);

            try
            {
                listener.Bind(ipEndPoint);
                listener.Listen(5);

                while(true)
                {
                    allDone.Reset();

                    listener.AcceptAsync(new SocketAsyncEventArgs()
                    {

                    });

                    allDone.WaitOne();
                }
            }
            catch (Exception ex)
            {

            }
        }
        public async ValueTask <ConnectionContext> AcceptAsync(CancellationToken cancellationToken = default)
        {
            while (true)
            {
                try {
                    var acceptSocket = await _listenSocket.AcceptAsync();

                    // Only apply no delay to Tcp based endpoints
                    if (acceptSocket.LocalEndPoint is IPEndPoint)
                    {
                        acceptSocket.NoDelay = _options.NoDelay;
                    }

                    var connection = new SocketConnection(acceptSocket, _memoryPool, _schedulers[_schedulerIndex], _trace, _options.MaxReadBufferSize, _options.MaxWriteBufferSize);

                    connection.Start();

                    _schedulerIndex = (_schedulerIndex + 1) % _numSchedulers;

                    return(connection);
                } catch (ObjectDisposedException) {
                    // A call was made to UnbindAsync/DisposeAsync just return null which signals we're done
                    return(null);
                } catch (SocketException e) when(e.SocketErrorCode == SocketError.OperationAborted)
                {
                    // A call was made to UnbindAsync/DisposeAsync just return null which signals we're done
                    return(null);
                } catch (SocketException) {
                    // The connection got reset while it was in the backlog, so we try again.
                    _trace.ConnectionReset(connectionId: "(null)");
                }
            }
        }
        public async System.Threading.Tasks.ValueTask <ConnectionContext> AcceptAsync(CancellationToken cancellationToken = default)
        {
            while (true)
            {
                try
                {
                    var acceptSocket = await _listenSocket.AcceptAsync();

                    acceptSocket.NoDelay = _options.NoDelay;

                    var connection = new SocketConnection(acceptSocket, _memoryPool, _schedulers.GetScheduler(), _trace);

                    connection.Start();

                    return(connection);
                }
                catch (ObjectDisposedException)
                {
                    // A call was made to UnbindAsync/DisposeAsync just return null which signals we're done
                    return(null);
                }
                catch (SocketException e) when(e.SocketErrorCode == SocketError.OperationAborted)
                {
                    // A call was made to UnbindAsync/DisposeAsync just return null which signals we're done
                    return(null);
                }
                catch (SocketException)
                {
                    // The connection got reset while it was in the backlog, so we try again.
                    _trace.ConnectionReset(connectionId: "(null)");
                }
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// 启动监听
        /// </summary>
        /// <param name="config">服务器配置</param>
        /// <returns></returns>
        public override bool Start(IServerConfig config)
        {
            m_ListenSocket = new System.Net.Sockets.Socket(this.Info.EndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                //关联终结地
                m_ListenSocket.Bind(this.Info.EndPoint);
                //设置监听最大连接数
                m_ListenSocket.Listen(m_ListenBackLog);

                m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);

                m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
                //初始化套接字操作
                SocketAsyncEventArgs acceptEventArg = new SocketAsyncEventArgs();
                m_AcceptSAE = acceptEventArg;
                //定义一个连接完成事件
                acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(acceptEventArg_Completed);
                if (!m_ListenSocket.AcceptAsync(acceptEventArg))
                {
                    ProcessAccept(acceptEventArg);
                }
                return true;
            }
            catch (Exception e)
            {
                OnError(e);
                return false;
            }
        }
Exemplo n.º 12
0
        public override void Start()
        {
            if (!Disposed)
            {
                FSocket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                FSocket.Bind(LocalEndPoint);
                FSocket.Listen(FBackLog * FAcceptThreads);

                //----- Begin accept new connections!
                int loopCount          = 0;
                SocketAsyncEventArgs e = null;

                for (int i = 1; i <= FAcceptThreads; i++)
                {
                    e            = new SocketAsyncEventArgs();
                    e.UserToken  = this;
                    e.Completed += new EventHandler <SocketAsyncEventArgs>(BeginAcceptCallbackAsync);

                    if (!FSocket.AcceptAsync(e))
                    {
                        BeginAcceptCallbackAsync(this, e);
                    }
                    ;

                    ThreadEx.LoopSleep(ref loopCount);
                }
            }
        }
Exemplo n.º 13
0
        public EndPointListener(
            IPAddress address, int port, bool secure, string certFolderPath, X509Certificate2 defaultCert)
        {
            if (secure)
            {
                _secure = secure;
                _cert   = getCertificate(port, certFolderPath, defaultCert);
                if (_cert == null)
                {
                    throw new ArgumentException("No server certificate found.");
                }
            }

            _endpoint     = new IPEndPoint(address, port);
            _prefixes     = new Dictionary <ListenerPrefix, HttpListener> ();
            _unregistered = new Dictionary <HttpConnection, HttpConnection> ();

            _socket = new System.Net.Sockets.Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            _socket.Bind(_endpoint);
            _socket.Listen(500);

            var args = new SocketAsyncEventArgs();

            args.UserToken  = this;
            args.Completed += onAccept;
            _socket.AcceptAsync(args);
        }
        /// <summary>
        /// Starts to listen
        /// </summary>
        /// <param name="config">The server config.</param>
        /// <returns></returns>
        public override bool Start(IServerConfig config)
        {
            m_ListenSocket = new Socket(this.Info.EndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                m_ListenSocket.Bind(this.Info.EndPoint);
                m_ListenSocket.Listen(m_ListenBackLog);

                m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
                m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
                //
                m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            
                SocketAsyncEventArgs acceptEventArg = new SocketAsyncEventArgs();
                acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(acceptEventArg_Completed);

                if (!m_ListenSocket.AcceptAsync(acceptEventArg))
                    ProcessAccept(acceptEventArg);

                return true;

            }
            catch (Exception e)
            {
                OnError(e);
                return false;
            }
        }
Exemplo n.º 15
0
		public void AcceptAsyncShouldUseAcceptSocketFromEventArgs()
		{
			var readyEvent = new ManualResetEvent(false);
			var mainEvent = new ManualResetEvent(false);
			var listenSocket = new Socket(
				AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			var serverSocket = new Socket(
					AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			Socket acceptedSocket = null;
			Exception ex = null;
			ThreadPool.QueueUserWorkItem(_ =>
			{
				SocketAsyncEventArgs asyncEventArgs;
				try {
					listenSocket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
					listenSocket.Listen(1);

					asyncEventArgs = new SocketAsyncEventArgs {AcceptSocket = serverSocket};
					asyncEventArgs.Completed += (s, e) =>
					{
						acceptedSocket = e.AcceptSocket;
						mainEvent.Set();
					};

				} catch (Exception e) {
					ex = e;
					return;
				} finally {
					readyEvent.Set();
				}

				try {
					if (listenSocket.AcceptAsync(asyncEventArgs))
						return;
					acceptedSocket = asyncEventArgs.AcceptSocket;
					mainEvent.Set();
				} catch (Exception e) {
					ex = e;
				}
			});
			Assert.IsTrue(readyEvent.WaitOne(1500));
			if (ex != null)
				throw ex;

			var clientSocket = new Socket(
				AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			clientSocket.Connect(listenSocket.LocalEndPoint);
			clientSocket.NoDelay = true;

			Assert.IsTrue(mainEvent.WaitOne(1500));
			Assert.AreEqual(serverSocket, acceptedSocket, "x");
			mainEvent.Reset();

			if (acceptedSocket != null)
				acceptedSocket.Close();

			listenSocket.Close();
			readyEvent.Close();
			mainEvent.Close();
		}
Exemplo n.º 16
0
    private void StartAccept(SocketAsyncEventArgs args)
    {
        args.AcceptSocket = null;

        if (!g_listener.AcceptAsync(args))
        {
            ProcessAccept(args);
        }
    }
Exemplo n.º 17
0
        void acceptAsync(Socket socket, SocketAsyncEventArgs e)
        {
            e.AcceptSocket = null;

            if (socket.AcceptAsync(e) == false)
            {
                acceptAsyncEvent_Completed(socket, e);
            }
        }
Exemplo n.º 18
0
        public void Accept(Socket ListenSock)
        {
            if (false == ListenSock.AcceptAsync(FAcceptEventArg))
            {

                OnCompleted(ListenSock, FAcceptEventArg);

            }
        }
Exemplo n.º 19
0
 public static async Task AcceptSocketAsync(Socket server, Func<Socket, NetworkStream, StreamReader, StreamWriter, Task> funcAsync)
 {
     using (Socket s = await server.AcceptAsync().ConfigureAwait(false))
     using (var stream = new NetworkStream(s, ownsSocket: false))
     using (var reader = new StreamReader(stream, Encoding.ASCII))
     using (var writer = new StreamWriter(stream, Encoding.ASCII))
     {
         await funcAsync(s, stream, reader, writer).ConfigureAwait(false);
     }
 }
Exemplo n.º 20
0
        private void AsyncWaitAccept(SocketAsyncEventArgs e)
        {
            e.AcceptSocket = null;

            bool willRaiseEvent = listenSocket.AcceptAsync(e);

            if (willRaiseEvent == false)
            {
                ProcessAccept(e);
            }
        }
Exemplo n.º 21
0
    private async Task AcceptConnectionsAsync()
    {
        while (!_acceptConnectionsToken.IsCancellationRequested)
        {
            var socketClient = new SocketClient();
            var linkedCts    = CancellationTokenSource.CreateLinkedTokenSource(socketClient.Token, _acceptConnectionsToken);

            try
            {
                var newClientSocket = await _serverSocket.AcceptAsync(_acceptConnectionsToken);

                var clientIp = newClientSocket.RemoteEndPoint?.ToString();

                Log.Logger.Information($"Подключился новый клиент: {clientIp}");

                await socketClient.CreateAsync(newClientSocket, _acceptConnectionsToken);

                _clientController.AddClient(clientIp, socketClient);

                _events.CallClientConnectedEvent(this, clientIp);

                // await _clientController.BroadcastAllAsync("Подключился новый клиент", _listenerToken);

                var _ = Task.Run(() => DataReceiverAsync(socketClient, _token), linkedCts.Token);
            }
            catch (Exception ex)
            {
                if (ex is TaskCanceledException ||
                    ex is OperationCanceledException ||
                    ex is ObjectDisposedException ||
                    ex is InvalidOperationException)
                {
                    _isListen = false;
                    // if (socketClient != null)
                    //     socketClient.Dispose();

                    Log.Logger.Information($"Stopped listening");
                    break;
                }
                else
                {
                    // if (socketClient != null)
                    //     socketClient.Dispose();

                    Log.Logger.Error($"Возникла ошибка во время ожидация новых подключений: {ex}");
                    continue;
                }
            }
        }

        _isListen = false;
    }
Exemplo n.º 22
0
 /// <summary>
 /// Start and listen ongoing TCP connections on the localhost on the given port
 /// </summary>
 /// <param name="port">port number of the connection. Use 0 for any availble port.</param>
 public ServerMock(int port)
 {
     var endpoint = new IPEndPoint(new IPAddress(new byte[] { 127, 0, 0, 1 }), port);
     _socket = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
     _socket.Bind(endpoint);
     ListenEndPoint = _socket.LocalEndPoint as IPEndPoint;
     _socket.Listen((int)SocketOptionName.MaxConnections);
     var acceptEventArgs = GetAcceptEventArgs();
     if (!_socket.AcceptAsync(acceptEventArgs))
         throw new Exception("Unable to listen on " + ListenEndPoint);
     _acceptedSockets = new List<Socket>();
     ResponseHeader = new byte[MemcacheResponseHeader.Size];
 }
Exemplo n.º 23
0
 private void start()
 {
     m_ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9001);
     m_ServerSocket.Bind(ipep);
     m_ServerSocket.Listen(20);
     SocketAsyncEventArgs args = new SocketAsyncEventArgs();
     args.Completed += new EventHandler<SocketAsyncEventArgs>(Accept_Completed);
     m_ServerSocket.AcceptAsync(args);
     while (true)
     {
     }
 }
Exemplo n.º 24
0
 public AwaitIo AcceptAsync(Socket listener, bool post_read_buffers = false)
 {
     if (post_read_buffers)
     {
         var ds = _data.GetSegmentToRead();
         int pos = ds.Count, bts = ds.Size - pos;
         SetBuffer(ds.Buffer, ds.Offset + pos, bts);
     }
     // see Recv() comments on SuppressFlow.
     var async = false;
     var aFC = ExecutionContext.SuppressFlow();
     try { async = listener.AcceptAsync(this); } finally { aFC.Undo(); }
     return CheckCompleted(async);
 }
Exemplo n.º 25
0
        void AcceptIteration()
        {
            const int BufferSize = 1024 * 1024;             //	won't ever be 1mb
            var       Accept     = new SocketAsyncEventArgs();

            Accept.Completed += OnAccept;
            //Recv.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0);

            //	returns if is pending, if false, it completed synchronously
            if (!Socket.AcceptAsync(Accept))
            {
                OnAccept(this.Socket, Accept);
            }
        }
Exemplo n.º 26
0
        private static void AcceptAsync(IntPtr info)
        {
            NSJSFunctionCallbackInfo arguments = NSJSFunctionCallbackInfo.From(info);
            bool success = false;

            do
            {
                SocketContext context = GetSocketContext(arguments.This);
                if (context == null)
                {
                    Throwable.ObjectDisposedException(arguments.VirtualMachine);
                    break;
                }
                SOCKET socket = context.Socket;
                if (socket == null || SocketExtension.CleanedUp(socket))
                {
                    Throwable.ObjectDisposedException(arguments.VirtualMachine);
                    break;
                }
                NSJSFunction callback = arguments.Length > 0 ? arguments[0] as NSJSFunction : null;
                try
                {
                    SocketAsyncEventArgs e = context.AcceptAsync;
                    if (e != null)
                    {
                        break;
                    }
                    e                   = new SocketAsyncEventArgs();
                    e.Completed        += ProcessAccept;
                    e.UserToken         = context;
                    context.AcceptAsync = e;
                    if (callback != null)
                    {
                        NSJSObject socketobject = arguments.This;
                        callback.CrossThreading     = true;
                        context.AcceptAsyncCallback = callback;
                    }
                    if (!socket.AcceptAsync(e))
                    {
                        ProcessAccept(socket, e);
                    }
                    success = true;
                }
                catch (Exception e)
                {
                    Throwable.Exception(arguments.VirtualMachine, e);
                }
            } while (false);
            arguments.SetReturnValue(success);
        }
Exemplo n.º 27
0
        public override void Initialize()
        {
            if (_socket != null) return;

              _socket = new Socket(_ipv6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
              _socket.ExclusiveAddressUse = true;
              _socket.Bind(new IPEndPoint(_ipv6 ? IPAddress.IPv6Any : IPAddress.Any, _port));
              _socket.Listen(100);

              var args = new SocketAsyncEventArgs();
              args.Completed += AcceptAsyncCompleted;

              _socket.AcceptAsync(args);
        }
Exemplo n.º 28
0
		void DoWork ()
		{
			serverSocket = new Socket (
				AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			serverSocket.Bind (new IPEndPoint (IPAddress.Loopback, 0));
			serverSocket.Listen (1);

			var async = new SocketAsyncEventArgs ();
			async.Completed += (s,e) => OnAccepted (e);

			readyEvent.Set ();

			if (!serverSocket.AcceptAsync (async))
				OnAccepted (async);
		}
Exemplo n.º 29
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);
      _socket.ExclusiveAddressUse = true;
      _socket.Bind(new IPEndPoint(IPAddress.Any, 943));
      _socket.Listen(100);

      var args = new SocketAsyncEventArgs();
      args.Completed += AcceptAsyncCompleted;

      _socket.AcceptAsync(args);
    }
Exemplo n.º 30
0
        void SocketAsyncEventArgs_AcceptCompleted(object sender, System.Net.Sockets.SocketAsyncEventArgs e)
        {
            if (e != null)
            {
                if (e.AcceptSocket != null && e.AcceptSocket.RemoteEndPoint != null && e.LastOperation == SocketAsyncOperation.Accept)
                {
                    Debug.WriteLine(e.AcceptSocket.RemoteEndPoint.ToString());
                    System.Net.Sockets.SocketAsyncEventArgs saea = new System.Net.Sockets.SocketAsyncEventArgs();
                    saea.Completed   += SocketAsyncEventArgs_ReceiveCompleted;
                    saea.AcceptSocket = e.AcceptSocket;
                    saea.UserToken    = e.AcceptSocket.RemoteEndPoint.ToString();
                    saea.SetBuffer(new byte[BufferSize], 0, BufferSize);
                    e.AcceptSocket.ReceiveAsync(saea);
                }
                else
                {
                    Debug.WriteLine("Stop");
                }
            }


            bool Crashed = false;

            try
            {
                Crashed = ServerSocket == null || ServerSocket.LocalEndPoint == null;
            }
            catch { }

            if (Crashed && _Status == ServerStatus.Running)
            {
                Clients.Clear();

                ServerSocket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
                ServerSocket.Bind(new IPEndPoint(IPAddress.Parse(Address), Port));
                ServerSocket.Listen(BackLog);
                Debug.WriteLine(String.Format("Listen at {0}:{1}", Address, Port));
                //
                SocketAsyncEventArgs_AcceptCompleted(null, null);
            }
            else if (ServerSocket != null)
            {
                System.Net.Sockets.SocketAsyncEventArgs saea = new System.Net.Sockets.SocketAsyncEventArgs();
                saea.Completed += SocketAsyncEventArgs_AcceptCompleted;
                ServerSocket.AcceptAsync(saea);
            }
        }
Exemplo n.º 31
0
        public static void Main(string[] args)
        {
            IPEndPoint serverPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);
            Socket serverSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            serverSocket.Bind (serverPoint);
            serverSocket.Listen (10);

            Console.WriteLine ("waiting for connection");
            SocketAsyncEventArgs ev = new SocketAsyncEventArgs ();
            ev.Completed += new EventHandler<SocketAsyncEventArgs> (Accept_Completed);
            serverSocket.AcceptAsync (ev);

            Console.ReadLine ();

            Console.WriteLine ("Bye~");
        }
Exemplo n.º 32
0
        public Server()
        {
            server = this;
            ReadItemSet();
            Socket _server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint _ipep = new IPEndPoint(IPAddress.Any, 50005);
            _server.Bind(_ipep);
            _server.Listen(20);
            Console.WriteLine("Handle of server process: " + _server.Handle.ToInt32());

            SocketAsyncEventArgs _args = new SocketAsyncEventArgs();
            _args.Completed += new EventHandler<SocketAsyncEventArgs>(Accept_Completed);

            _server.AcceptAsync(_args);
            SetTimer();
            DataInput();
        }
		public EndPointListener (IPAddress addr, int port, bool secure)
		{
			if (secure) {
				this.secure = secure;
				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 ();
		}
Exemplo n.º 34
0
 void AcceptLoop(Sockets.SocketAsyncEventArgs EventStatement)
 {
     try {
         if (EventStatement == null)
         {
             EventStatement            = new Sockets.SocketAsyncEventArgs();
             EventStatement.Completed += AcceptEvent_Completed;
         }
         else
         {
             EventStatement.AcceptSocket = null;
         }
         bool EventTrigger = Socket.AcceptAsync(EventStatement);;
         if (!EventTrigger)
         {
             AcceptClientObject(EventStatement);
         }
     }
     catch (System.Exception) { }
 }
Exemplo n.º 35
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> ();
		}
Exemplo n.º 36
0
 /// <summary>
 /// 从客户端开始接受一个连接操作
 /// </summary>
 private void StartAccept(SocketAsyncEventArgs asyniar)
 {
     if (asyniar == null)
     {
         asyniar            = new SocketAsyncEventArgs();
         asyniar.Completed += new EventHandler <SocketAsyncEventArgs>(OnAcceptCompleted);
     }
     else
     {
         //socket must be cleared since the context object is being reused
         asyniar.AcceptSocket = null;
     }
     _maxAcceptedClients.WaitOne();
     if (!_serverSocket.AcceptAsync(asyniar))
     {
         ProcessAccept(asyniar);
         //如果I/O挂起等待异步则触发AcceptAsyn_Asyn_Completed事件
         //此时I/O操作同步完成,不会触发Asyn_Completed事件,所以指定BeginAccept()方法
     }
 }
Exemplo n.º 37
0
 public void start_accept(SocketAsyncEventArgs acceptEventArg)
 {
     if (acceptEventArg == null)
     {
         acceptEventArg            = new SocketAsyncEventArgs();
         acceptEventArg.UserToken  = new AsyncUserToken();
         acceptEventArg.Completed += new EventHandler <SocketAsyncEventArgs>(acceptEventArgs_completed);
     }
     else
     {
         // socket must be cleared since the context object is being reused
         acceptEventArg.AcceptSocket = null;
     }
     m_numAcceptedClientsMax.WaitOne();
     //return false if the I/O operation completed synchronously.
     if (!m_listenSocket.AcceptAsync(acceptEventArg))
     {
         process_accept(acceptEventArg);
     }
 }
Exemplo n.º 38
0
        /// <summary>
        /// 开始监听
        /// </summary>
        protected void StartAccept(SocketAsyncEventArgs acceptEventArg)
        {
            if (acceptEventArg == null)
            {
                acceptEventArg            = new SocketAsyncEventArgs();
                acceptEventArg.Completed += AcceptEventCompleted;
            }
            else
            {
                // socket must be cleared since the context object is being reused
                acceptEventArg.AcceptSocket = null;
            }

            bool willRaiseEvent = _tcpListen.AcceptAsync(acceptEventArg);

            if (!willRaiseEvent)
            {
                ProcessAccept(acceptEventArg);
            }
        }
Exemplo n.º 39
0
        protected override void DoInitilize()
        {
            if (socket != null) return;

            socket = new Socket(IpV6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork, SocketType.Stream,
                ProtocolType.Tcp);

            // allow other apps listen the same port
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, false);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

            var endpoint = new IPEndPoint(IpV6 ? IPAddress.IPv6Any : IPAddress.Any, Port);
            socket.Bind(endpoint);
            socket.Listen(100);
            socket.ReceiveBufferSize = BufferSize;

            var args = new SocketAsyncEventArgs();
            args.Completed += AcceptAsyncCompleted;

            socket.AcceptAsync(args);
        }
Exemplo n.º 40
0
        private void Accept(object sender, SocketAsyncEventArgs e)
        {
            var ip     = e.AcceptSocket.RemoteEndPoint;
            var ioArgs = argsPool.Pop();

            ioArgs.AcceptSocket = e.AcceptSocket;
            var userData = new UserData()
            {
                ConnectTime    = DateTime.Now,
                RemoteEndPoint = ip,
                Socket         = e.AcceptSocket,
                ReceiveArgs    = ioArgs
            };

            e.AcceptSocket.ReceiveAsync(ioArgs);
            Console.WriteLine($"[{ip.ToString()} {userData.UserId.ToString()}] is connected");
            ioArgs.UserToken             = userData;
            ClientPool[userData.UserId]  = userData;
            AcceptEventArgs.AcceptSocket = null;
            ListenSocket.AcceptAsync(AcceptEventArgs);
        }
Exemplo n.º 41
0
 private static void ProcessAccept(object sender, SocketAsyncEventArgs e)
 {
     try
     {
         SocketContext context = e.UserToken as SocketContext;
         do
         {
             SOCKET client = e.AcceptSocket;
             SOCKET server = (SOCKET)sender;
             e.AcceptSocket = null;
             do
             {
                 if (context == null)
                 {
                     break;
                 }
                 NSJSFunction function = context.AcceptAsyncCallback;
                 NSJSObject   socket   = context.This;
                 if (function == null)
                 {
                     break;
                 }
                 NSJSVirtualMachine machine = function.VirtualMachine;
                 if (machine == null)
                 {
                     break;
                 }
                 machine.Join((sendert, statet) => function.Call(socket,
                                                                 NSJSInt32.New(machine, unchecked ((int)e.SocketError)),
                                                                 NSJSValue.NullMerge(machine, New(machine, client))));
             } while (false);
             if (!server.AcceptAsync(e))
             {
                 ProcessAccept(server, e);
             }
         } while (false);
     }
     catch (Exception) { }
 }
Exemplo n.º 42
0
        /// <summary>
        /// Server Listen 을 시작한다.
        /// </summary>
        /// <param name="connectionStr">"ListenIP:Port" 형태로 넣는다.</param>
        public void Start(string connectionStr, Action<TcpSocket> onOpen, Action<TcpSocket> onClose, Action<TcpSocket, string> onMessage)
        {
            string[] splitStr = connectionStr.Split(':');
            if (splitStr.Length != 2)
            {
                throw new ArgumentException();
            }

            IPAddress ipAddress = IPAddress.Parse(splitStr[0]);
            if (null == ipAddress)
            {
                throw new ArgumentException();
            }

            int port = 0;
            if (!int.TryParse(splitStr[1], out port))
            {
                throw new ArgumentException();
            }

            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);

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

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

            SocketAsyncEventArgs e = new SocketAsyncEventArgs();
            object[] actionArray = new object[] { onOpen, onClose, onMessage };
            e.UserToken = actionArray;
            e.Completed += AcceptCallback;

            if (!listener.AcceptAsync(e))
            {
                AcceptCallback(listener, e);
            }
        }
Exemplo n.º 43
0
        public async void Start(int port)
        {
            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();
                    var session = SessionManager.CreateSession(clientSocket);
                    session.StartReceive();
                }
            }
            catch (Exception e)
            {
                Logger.Write(e);
            }
        }
Exemplo n.º 44
0
        public async void Start()
        {
            try
            {
                var listener = new Socket(AddressFamily.InterNetwork,
                                          SocketType.Stream, ProtocolType.Tcp);
                var localEndPoint = new IPEndPoint(IPAddress.Any, Port);

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

                while (true)
                {
                    var clientSocket = await listener.AcceptAsync();
                    ProcessSocket(clientSocket);
                }
            }
            catch (Exception e)
            {
                Logger.Write(e);
            }
        }
Exemplo n.º 45
0
        /*开始接收套接字*/
        private void startAccept(SocketAsyncEventArgs socketAsync = null)
        {
            if (!IsRun || listen == null)
            {
                return;
            }

            if (socketAsync == null)
            {
                socketAsync            = new SocketAsyncEventArgs();
                socketAsync.Completed += OnAcceptNewConnection;
            }
            else
            {
                socketAsync.AcceptSocket = null;
            }

            if (!listen.AcceptAsync(socketAsync))
            {
                OnAcceptNewConnection(listen, socketAsync);
            }
        }
Exemplo n.º 46
0
        static void Main(string[] args)
        {
            Console.Write("포트번호입력(1024 - 65535): ");
            int port = int.Parse(Console.ReadLine());
            IPEndPoint myAddr = new IPEndPoint(IPAddress.Any, port);
            Socket server = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream,
                ProtocolType.Tcp);
            server.Bind(myAddr);

            server.Listen(10);
            SocketAsyncEventArgs args = new SocketAsyncEventArgs();
            args.Completed += new EventHandler(Accept_Completed);

            server.AcceptAsync(args);
            Console.WriteLine("서버 시작");

            while (true)
            {
                Socket client = server.Accept();
                Console.WriteLine("클라이언트 {0} 접속",
                    client.RemoteEndPoint.ToString());
                NetworkStream ns = new NetworkStream(client);

                int len;
                string msg;
                while ((len = ns.Read(buf, 0, buf.Length)) != 0)
                {
                    msg = Encoding.UTF8.GetString(buf, 0, len);
                    Console.WriteLine("수신: {0}" , msg);
                    ns.Write(buf, 0, len);
                }
                Console.WriteLine("클라이언트 {0} 접속종료",
                    client.RemoteEndPoint.ToString());
                ns.Close();
                client.Close();
            }
        }
Exemplo n.º 47
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);
            }
        }
Exemplo n.º 48
0
        public void Start(IPEndPoint ipEndPoint)
        {
            Console.Write("Buffer initializing...");
            bufferManager = new BufferManager(MaxConnectCount * BufferSize * opsToPreAlloc, BufferSize);
            bufferManager.InitBuffer();
            Console.WriteLine("Complete!");
            Console.Write("ConnectionPool initializing...");
            for (int i = 0; i < MaxConnectCount; i++)
            {
                var args = new SocketAsyncEventArgs();
                bufferManager.SetBuffer(args);
                args.Completed += Receive;
                argsPool.Push(args);
            }
            Console.WriteLine("Complete!");
            ListenSocket = new SysSocket.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            ListenSocket.Bind(ipEndPoint);

            ListenSocket.Listen(MaxConnectCount);
            ListenSocket.AcceptAsync(AcceptEventArgs);
            Console.WriteLine($"TcpService now listening [{ipEndPoint.Address.ToString()}:{ipEndPoint.Port}]");
            Console.WriteLine("TCP Service is runing");
        }
Exemplo n.º 49
0
        public void Bind()
        {
            _listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            var localEndPoint = new IPEndPoint(_bind.IpAddress, _bind.Port);
            _listenSocket.Bind(localEndPoint);
            _listenSocket.Listen((int) _bind.MaximumPendingConnections);

            _manualResetEvent = new ManualResetEvent(false);
            _manualResetEvent.Reset();

            _connectionWorkersPool = _connectionWorkersPoolFactory.GetSocketAsyncEventArgsPool(
                _bind.MaximumOpenedConnections,
                (uint)Environment.SystemPageSize, IoCompleted);

            var acceptEventArg = new SocketAsyncEventArgs();
            acceptEventArg.Completed += AcceptEventArg_Completed;

            _manualResetEvent.WaitOne();
            if (_listenSocket.AcceptAsync(acceptEventArg)) // if performed synchroniosly
            {
                ProcessAccept(acceptEventArg);
            }
        }
Exemplo n.º 50
0
        /// <summary>
        /// Intizializes the <see cref="ILogProvider"/>.
        /// </summary>
        /// <param name="logHandler">The <see cref="ILogHandler"/> that may handle incomming <see cref="LogMessage"/>s.</param>
        public override void Initialize(ILogHandler logHandler)
        {
            base.Initialize(logHandler);

              try
              {
            mSocket = new Socket(
            AddressFamily.InterNetwork
              , SocketType.Stream
              , ProtocolType.Tcp);

            mSocket.ExclusiveAddressUse = true;
            mSocket.ReceiveBufferSize   = RECEIVE_BUFFER_SIZE;

            mSocket.Bind(new IPEndPoint(
            IPAddress.Any
              , mPort));

            mSocket.Listen(100);

            SocketAsyncEventArgs socketEvent = new SocketAsyncEventArgs();
            socketEvent.Completed += SocketEventCompleted;

            mSocket.AcceptAsync(socketEvent);
              }
              catch (Exception ex)
              {
            Logger.Warn(ex.Message);
              }
        }
Exemplo n.º 51
0
 bool Utils.Wrappers.Interfaces.ISocket.AcceptAsync(SocketAsyncEventArgs e)
 {
     return(InternalSocket.AcceptAsync(e));
 }
Exemplo n.º 52
0
 public static Task <Socket> AcceptAsync(this Socket socket) =>
 socket.AcceptAsync((Socket)null);
Exemplo n.º 53
0
 public static Task <Socket> AcceptAsync(this Socket socket, Socket acceptSocket) =>
 socket.AcceptAsync(acceptSocket);
 public static IAsyncResult BeginAccept(this System.Net.Sockets.Socket socket
                                        , AsyncCallback callback, object state)
 {
     return(socket.AcceptAsync().AsApm(callback, state));
 }
Exemplo n.º 55
-1
        void initilaze()
        {
            m_Display = new List<StringBuilder>();
            sever = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sever.Bind(new IPEndPoint(IPAddress.Any, 3000));
            sever.Listen(20);
            SocketAsyncEventArgs sockasync = new SocketAsyncEventArgs();
            SocketAsyncEventArgs sockasync1 = new SocketAsyncEventArgs();
            sockasync.Completed += new EventHandler<SocketAsyncEventArgs>(SocketAccept);

            sever.AcceptAsync(sockasync);

            Connect();
        }