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


C# Sockets.SocketAsyncEventArgs类代码示例

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


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

示例1: Listener

		public Listener(IPEndPoint ipep)
		{
			m_Accepted = new Queue<Socket>();
			m_AcceptedSyncRoot = ((ICollection)m_Accepted).SyncRoot;

			m_Listener = Bind(ipep);

			if (m_Listener == null)
			{
				return;
			}

			DisplayListener();

#if NewAsyncSockets
			m_EventArgs = new SocketAsyncEventArgs();
			m_EventArgs.Completed += new EventHandler<SocketAsyncEventArgs>( Accept_Completion );
			Accept_Start();
            #else
			m_OnAccept = OnAccept;
			try
			{
				IAsyncResult res = m_Listener.BeginAccept(m_OnAccept, m_Listener);
			}
			catch (SocketException ex)
			{
				NetState.TraceException(ex);
			}
			catch (ObjectDisposedException)
			{ }
#endif
		}
开发者ID:Crome696,项目名称:ServUO,代码行数:32,代码来源:Listener.cs

示例2: ServerConnection

        /// <summary>
        /// A connection to our server, always listening asynchronously.
        /// </summary>
        /// <param name="socket">The Socket for the connection.</param>
        /// <param name="args">The SocketAsyncEventArgs for asyncronous recieves.</param>
        /// <param name="dataReceived">A callback invoked when data is recieved.</param>
        /// <param name="disconnectedCallback">A callback invoked on disconnection.</param>
        public ServerConnection(Socket socket, SocketAsyncEventArgs args, DataReceivedCallback dataReceived,
            DisconnectedCallback disconnectedCallback)
        {
            logger = new ElibLogging("data");
            this.AuthorizationType = Securtiy.AuthorizationType.Anonymous;
            lock (this)
            {
                var remotIP = socket.RemoteEndPoint as IPEndPoint;
                var localIP = socket.LocalEndPoint as IPEndPoint;
                State state = new State()
                {
                    socket = socket,
                    dataReceived = dataReceived,
                    disconnectedCallback = disconnectedCallback,
                    Device = new Device()
                    {
                        RemoteIP = remotIP.Address.ToString(),
                        LocalIP = localIP.Address.ToString()
                    }
                };

                eventArgs = args;
                eventArgs.Completed += ReceivedCompleted;
                eventArgs.UserToken = state;

                ListenForData(eventArgs);
            }
        }
开发者ID:kainhong,项目名称:CurrencyStore,代码行数:35,代码来源:ServerConnection.cs

示例3: Init

        // Initializes the server by preallocating reusable buffers and
        // context objects.  These objects do not need to be preallocated
        // or reused, but it is done this way to illustrate how the API can
        // easily be used to create reusable objects to increase server performance.
        //
        public void Init()
        {
            // Allocates one large byte buffer which all I/O operations use a piece of.  This gaurds
            // against memory fragmentation
            m_bufferManager.InitBuffer();

            // preallocate pool of SocketAsyncEventArgs objects
            SocketAsyncEventArgs readWriteEventArg;

            for (int i = 0; i < m_numConnections; i++)
            {
                //Pre-allocate a set of reusable SocketAsyncEventArgs
                readWriteEventArg = new SocketAsyncEventArgs();
                readWriteEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed);
                readWriteEventArg.UserToken = new AsyncUserToken();

                //((AsyncUserToken) readWriteEventArg.UserToken).name = "e" + i;

                // assign a byte buffer from the buffer pool to the SocketAsyncEventArg object
                m_bufferManager.SetBuffer(readWriteEventArg);

                // add SocketAsyncEventArg to the pool
                m_readWritePool.Push(readWriteEventArg);
            }
        }
开发者ID:vls,项目名称:hp2p,代码行数:30,代码来源:Server.cs

示例4: StartConnectAsync

        // Called by Socket to kick off the ConnectAsync process.  We'll complete the user's SAEA
        // when it's done.  Returns true if the operation will be asynchronous, false if it has failed synchronously
        public bool StartConnectAsync(SocketAsyncEventArgs args, DnsEndPoint endPoint)
        {
            lock (lockObject)
            {
                GlobalLog.Assert(endPoint.AddressFamily == AddressFamily.Unspecified ||
                     endPoint.AddressFamily == AddressFamily.InterNetwork ||
                     endPoint.AddressFamily == AddressFamily.InterNetworkV6,
                     "MultipleConnectAsync.StartConnectAsync(): Unexpected endpoint address family - " + endPoint.AddressFamily.ToString());

                this.userArgs = args;
                this.endPoint = endPoint;

                // If Cancel() was called before we got the lock, it only set the state to Canceled: we need to
                // fail synchronously from here.  Once State.DnsQuery is set, the Cancel() call will handle calling AsyncFail.
                if (state == State.Canceled)
                {
                    SyncFail(new SocketException(SocketError.OperationAborted));
                    return false;
                }

                GlobalLog.Assert(state == State.NotStarted, "MultipleConnectAsync.StartConnectAsync(): Unexpected object state");

                state = State.DnsQuery;

                IAsyncResult result = Dns.BeginGetHostAddresses(endPoint.Host, new AsyncCallback(DnsCallback), null);
                if (result.CompletedSynchronously)
                {
                    return DoDnsCallback(result, true);
                }
                else
                {
                    return true;
                }
            }
        }
开发者ID:REALTOBIZ,项目名称:mono,代码行数:37,代码来源:_MultipleConnectAsync.cs

示例5: ConnectTo

		public void ConnectTo(string ip, int port)
		{

			State = ConnectionState.NotConnected;

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

			IPAddress[] ips = Dns.GetHostAddresses(ip);
			var addr = ips[0];
			var hostEndPoint = new IPEndPoint(addr, port);

			var connectEA = new SocketAsyncEventArgs();

			connectEA.RemoteEndPoint = hostEndPoint;
			connectEA.Completed += (object sender, SocketAsyncEventArgs e)=>{

				switch (e.LastOperation)
				{
				case SocketAsyncOperation.Connect:
					UnityEngine.Debug.Log("Connect success");
					break;
				default:
					throw new ArgumentException("The last operation completed on the socket was not a receive or send");
				}

				connectEA.Dispose();

				State = ConnectionState.Connected;

			};

			State = ConnectionState.Connecting;

			socket.ConnectAsync(connectEA);
		}
开发者ID:xclouder,项目名称:godbattle,代码行数:35,代码来源:NetworkInterface.cs

示例6: Accept_Completed

        private void Accept_Completed(object sender, SocketAsyncEventArgs e)
        {
            e.Completed -= Accept_Completed;

            if (e.SocketError != SocketError.Success)
            {
                var error = string.Format("There was an error accepting a socket connection ({0}).",
                    Enum.GetName(typeof(SocketError), e.SocketError));
                OnConnectionAccepted(new ConnectionAcceptedEventArgs(error));
                return;
            }

            var clientConnection = new ClientConnection(e.AcceptSocket);
            try
            {
                OnConnectionAccepted(new ConnectionAcceptedEventArgs(clientConnection));
                clientConnection.ShutdownAndClose();
            }
            finally
            {
                ((IDisposable)clientConnection).Dispose();
            }

            OnConnectionClosed();
            AcceptIncomingConnection();
        }
开发者ID:jprice628,项目名称:Sketch,代码行数:26,代码来源:ConnectionListener.cs

示例7: InitializeAsync

        internal async Task InitializeAsync()
        {
            await Task.Run(() =>
            {
                var args = new SocketAsyncEventArgs
                {
                    UserToken = _socket,
                    RemoteEndPoint = _endPoint
                };

                args.Completed += async (sender, eventArgs) =>
                {
                    if (((Socket)sender).Connected)
                    {
                        _isConnected = true;

                        await _display.WriteAsync("NTRIP Connected");

                        await Task.Delay(500);
                    }
                    else
                    {
                        _isConnected = false;

                        await _display.WriteAsync("NTRIP Connection failed");
                    }
                };

                _socket.ConnectAsync(args);
            }).ConfigureAwait(false);
        }
开发者ID:Slimordium,项目名称:Hexapi_Hexapod,代码行数:31,代码来源:NtripClient.cs

示例8: BufferPool_CheckIn_Resets_SocketArg_Data_Buffer

 public void BufferPool_CheckIn_Resets_SocketArg_Data_Buffer()
 {
     var socketArg = new SocketAsyncEventArgs();
     BufferPool.Instance.CheckOut(socketArg);
     BufferPool.Instance.CheckIn(socketArg);
     Assert.IsNull(socketArg.Buffer);
 }
开发者ID:luuksommers,项目名称:oswos,代码行数:7,代码来源:BufferPoolTests.cs

示例9: UdpSocketWrapper

 /// <summary>
 /// Initializes a new instance of the <see cref="UdpSocketWrapper"/> class.
 /// </summary>
 public UdpSocketWrapper()
 {
     // operation arguments
     var args = new SocketAsyncEventArgs();
     args.Completed += SocketAsyncEventArgs_Completed;
     _socketOperation = args;
 }
开发者ID:porter1130,项目名称:WP8-DEMO,代码行数:10,代码来源:UdpSocketWrapper.cs

示例10: SocketAsyncEventArgsProxy

 public SocketAsyncEventArgsProxy(SocketAsyncEventArgs socketEventArgs, bool isRecyclable)
 {
     SocketEventArgs = socketEventArgs;
     OrigOffset = socketEventArgs.Offset;
     SocketEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(SocketEventArgs_Completed);
     IsRecyclable = isRecyclable;
 }
开发者ID:huamanhtuyen,项目名称:TagLo2,代码行数:7,代码来源:SocketAsyncEventArgsProxy.cs

示例11: SocketAsyncEventArgsDecorator

        public SocketAsyncEventArgsDecorator(SocketAsyncEventArgs socketAsyncEventArgs)
        {
            if (socketAsyncEventArgs == null)
                throw new ArgumentNullException("socketAsyncEventArgs");

            this.socketAsyncEventArgs = socketAsyncEventArgs;
        }
开发者ID:vgrigoriu,项目名称:Redis.SilverlightClient,代码行数:7,代码来源:SocketAsyncEventArgsDecorator.cs

示例12: AllocNewAsyncArgs

 SocketAsyncEventArgs AllocNewAsyncArgs()
 {
     SocketAsyncEventArgs args = new SocketAsyncEventArgs();
     args.Completed += m_receiveCompleteHandler;
     
     return args;
 }                
开发者ID:DM-TOR,项目名称:nhin-d,代码行数:7,代码来源:UdpServer.cs

示例13: OnEvent

 public override bool OnEvent(SocketAsyncEventArgs e)
 {
     if (Protocol.IsEnqueueForDelete || Protocol.TimePeriodElapsed()) return true;
     Logger.FATAL("Unable to handle TimeElapsed event");
     IOHandlerManager.EnqueueForDelete(this);
     return false;
 }
开发者ID:langhuihui,项目名称:csharprtmp,代码行数:7,代码来源:IOTimer.cs

示例14: Accept_Completed

        private void Accept_Completed(object sender, SocketAsyncEventArgs e)
        {
            Socket ClientSocket = e.AcceptSocket;
            Console.WriteLine("Accepting connection");

            byte[] bytesFrom = new byte[LENGTH.MAX_PACKET_LEN];
            string dataFromClient = null;
            ClientSocket.Receive(bytesFrom);
            dataFromClient = System.Text.Encoding.UTF8.GetString(bytesFrom);
            ChatProtocol chatProtocol = JsonConvert.DeserializeObject<ChatProtocol>(dataFromClient);

            socketToClient.Add(ClientSocket, chatProtocol.sender_id);
            clientToSocket.Add(chatProtocol.sender_id, ClientSocket);

            Console.WriteLine(chatProtocol.sender_id + " Joined ");

            SocketAsyncEventArgs args = new SocketAsyncEventArgs();
            szData = new byte[1024];
            args.SetBuffer(szData, 0, 1024);
            args.Completed
                += new EventHandler<SocketAsyncEventArgs>(Receive_Completed);
            ClientSocket.ReceiveAsync(args);

            e.AcceptSocket = null;
            m_ServerSocket.AcceptAsync(e);
        }
开发者ID:yguhan,项目名称:SmileWorld,代码行数:26,代码来源:Program.cs

示例15: TcpChannel

        /// <summary>
        ///     Initializes a new instance of the <see cref="TcpChannel" /> class.
        /// </summary>
        /// <param name="readBuffer">Buffer used for our reading.</param>
        /// <param name="encoder">Used to encode messages before they are put in the MicroMessage body of outbound messages.</param>
        /// <param name="decoder">
        ///     Used to decode the body of incoming MicroMessages. The <c>MessageReceived</c> delegate will be
        ///     overridden by this class.
        /// </param>
        public TcpChannel(IBufferSlice readBuffer, IMessageEncoder encoder, IMessageDecoder decoder) {
            if (readBuffer == null) throw new ArgumentNullException("readBuffer");
            if (encoder == null) throw new ArgumentNullException("encoder");
            if (decoder == null) throw new ArgumentNullException("decoder");

            _readArgs = new SocketAsyncEventArgs();
            _readArgs.SetBuffer(readBuffer.Buffer, readBuffer.Offset, readBuffer.Capacity);
            _readArgs.Completed += OnReadCompleted;
            _readArgsWrapper = new SocketAsyncEventArgsWrapper(_readArgs);

            _encoder = encoder;
            _decoder = decoder;
            _decoder.MessageReceived = OnMessageReceived;

            _writeArgs = new SocketAsyncEventArgs();
            _writeArgs.Completed += OnSendCompleted;
            _writeArgsWrapper = new SocketAsyncEventArgsWrapper(_writeArgs);

            _sendCompleteAction = (channel, message) => { };
            _disconnectAction = (channel, exception) => { };
            ChannelFailure = (channel, error) => HandleDisconnect(SocketError.ProtocolNotSupported);

            RemoteEndpoint = EmptyEndpoint.Instance;
            ChannelId = GuidFactory.Create().ToString();
            Data = new ChannelData();
        }
开发者ID:Tochemey,项目名称:NetFreeSwitch.Framework,代码行数:35,代码来源:TcpChannel.cs


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