当前位置: 首页>>代码示例>>C#>>正文


C# Socket.AcceptAsync方法代码示例

本文整理汇总了C#中System.Net.Sockets.Socket.AcceptAsync方法的典型用法代码示例。如果您正苦于以下问题:C# Socket.AcceptAsync方法的具体用法?C# Socket.AcceptAsync怎么用?C# Socket.AcceptAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.Sockets.Socket的用法示例。


在下文中一共展示了Socket.AcceptAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Start

        /// <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;
            }
        }
开发者ID:babywzazy,项目名称:Server,代码行数:36,代码来源:TcpAsyncSocketListener.cs

示例2: Listen

        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);
            }
        }
开发者ID:juney1110,项目名称:AegisNetwork,代码行数:30,代码来源:Acceptor.cs

示例3: StartListening

        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)
            {

            }
        }
开发者ID:moszinet,项目名称:HomeAutomation,代码行数:27,代码来源:WebServer.cs

示例4: EndPointListener

        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> ();
        }
开发者ID:richardfeng,项目名称:UnitySocketIO-WebSocketSharp,代码行数:26,代码来源:EndPointListener.cs

示例5: Initialize

        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);
            }
        }
开发者ID:steforster,项目名称:Remact.Net.Bms1Serializer,代码行数:26,代码来源:TcpStreamService.cs

示例6: Listen

        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);
                }
            }
        }
开发者ID:porter1130,项目名称:WP8-DEMO,代码行数:32,代码来源:TcpSocketWrapper.Server.cs

示例7: Start

        /// <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;
            }
        }
开发者ID:kinghuc,项目名称:521266750_qq_com,代码行数:34,代码来源:TcpAsyncSocketListener.cs

示例8: AcceptAsyncShouldUseAcceptSocketFromEventArgs

		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();
		}
开发者ID:ItsVeryWindy,项目名称:mono,代码行数:60,代码来源:SocketAcceptAsyncTest.cs

示例9: acceptAsync

        void acceptAsync(Socket socket, SocketAsyncEventArgs e)
        {
            e.AcceptSocket = null;

            if (socket.AcceptAsync(e) == false)
            {
                acceptAsyncEvent_Completed(socket, e);
            }
        }
开发者ID:W8023Y2014,项目名称:jsion,代码行数:9,代码来源:SocketAccepter.cs

示例10: Accept

        public void Accept(Socket ListenSock)
        {
            if (false == ListenSock.AcceptAsync(FAcceptEventArg))
            {

                OnCompleted(ListenSock, FAcceptEventArg);

            }
        }
开发者ID:lythm,项目名称:orb3d,代码行数:9,代码来源:GSSession.cs

示例11: AcceptSocketAsync

 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);
     }
 }
开发者ID:tstringer,项目名称:corefx,代码行数:10,代码来源:LoopbackServer.cs

示例12: ServerMock

 /// <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];
 }
开发者ID:mindis,项目名称:memcache-driver,代码行数:17,代码来源:ServerMock.cs

示例13: start

 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)
     {
     }
 }
开发者ID:yguhan,项目名称:SmileWorld,代码行数:13,代码来源:gameRoom.cs

示例14: AcceptAsync

 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);
 }
开发者ID:Dataflow-Software,项目名称:Dataflow.NET,代码行数:14,代码来源:SaeSocket.cs

示例15: Initialize

        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);
        }
开发者ID:pmorton,项目名称:Log2Console,代码行数:14,代码来源:TcpReceiver.cs


注:本文中的System.Net.Sockets.Socket.AcceptAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。