3

サーバーに接続する簡単なアプリケーションを作成しています。ただし、単純なチャット コマンドも送信したいと考えています (以下をConsole.ReadLine参照)。string Message = Console.ReadLine();ただし、このスクリプトはでブロックされているため、 にアクセスできません bytesRead = clientStream.Read(message, 0, 4096);

このスクリプトを続行したいのですが、着信バイトがある場合はそれらを処理する必要があり (現在のように)、着信バイトがない場合はスクリプトを通過してユーザー入力を待つ必要があります)。これはどのように達成できますか?

        TcpClient tcpClient = (TcpClient)client;
        NetworkStream clientStream = tcpClient.GetStream();

        byte[] message = new byte[4096];
        int bytesRead;

        while (true)
        {
            bytesRead = 0;

            try
            {
                // Blocks until a client sends a message                    
                bytesRead = clientStream.Read(message, 0, 4096);
            }
            catch (Exception)
            {
                // A socket error has occured
                break;
            }

            if (bytesRead == 0)
            {
                // The client has disconnected from the server
                break;
            }

            // Message has successfully been received
            ASCIIEncoding encoder = new ASCIIEncoding();

            // Output message
            Console.WriteLine("To: " + tcpClient.Client.LocalEndPoint);
            Console.WriteLine("From: " + tcpClient.Client.RemoteEndPoint);
            Console.WriteLine(encoder.GetString(message, 0, bytesRead));

            // Return message
            string Message = Console.ReadLine();
            if (Message != null)
            {
                byte[] buffer = encoder.GetBytes(Message);
                clientStream.Write(buffer, 0, buffer.Length);
                clientStream.Flush();
            }
4

1 に答える 1

11

DataAvailableプロパティを使用してみてください。ソケットで待機しているものがあるかどうかがわかります。Readfalse の場合は、呼び出しを行わないでください。

于 2012-05-23T11:56:44.547 に答える