Пример #1
0
        private void OnReceiveCompleted(object sender, SocketAsyncEventArgs e)
        {
            if (e.SocketError == SocketError.OperationAborted)
            {
                return;
            }

            Socket socket = sender as Socket;

            if (e.SocketError == SocketError.Success && e.BytesTransferred > 0)
            {
                string ipAdress      = socket.RemoteEndPoint.ToString();
                int    lengthBuffer  = e.BytesTransferred;
                byte[] receiveBuffer = e.Buffer;
                byte[] buffer        = new byte[lengthBuffer];
                Buffer.BlockCopy(receiveBuffer, 0, buffer, 0, lengthBuffer);

                //string msg = Encoding.Unicode.GetString(buffer);
                //Console.WriteLine("Client : receive message[ {0} ],from Server[ {1} ]", msg, ipAdress);

                OnReceiveHandle?.Invoke(buffer);

                socket.ReceiveAsync(e);
            }
            else if (e.SocketError == SocketError.ConnectionReset && e.BytesTransferred == 0)
            {
                Console.WriteLine("Client: 伺服器斷開連接 ");
            }
            else
            {
                return;
            }
        }
Пример #2
0
        /// <summary>
        /// This method is invoked when an asynchronous receive operation completes.
        /// If the remote host closed the connection, then the socket is closed.
        /// If data was received then the data is echoed back to the client.
        /// </summary>
        /// <param name="e"></param>
        private void ProcessReceive(SocketAsyncEventArgs e)
        {
            AsyncUserToken token = e.UserToken as AsyncUserToken;

            // e.BytesTransferred获取套接字操作中传输的字节数。
            if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
            {
                token.ActiveDateTime = DateTime.Now;

                int    lengthBuffer  = e.BytesTransferred;
                byte[] receiveBuffer = e.Buffer;
                byte[] buffer        = new byte[lengthBuffer];
                Buffer.BlockCopy(receiveBuffer, e.Offset, buffer, 0, lengthBuffer);
                OnReceiveHandle?.Invoke(token.ID, buffer);

                bool willRaiseEvent = token.AcceptSocket.ReceiveAsync(e);
                if (!willRaiseEvent)
                {
                    ProcessReceive(e);
                }
            }
            else
            {
                CloseClientSocket(e);
            }
        }