C# 使用 NetworkStream 进行异步读写

发布于 2024-11-30 11:01:19 字数 2422 浏览 2 评论 0原文

我构建了一个服务器,它接收来自客户端的请求并根据请求类型给出响应。如果请求类型是流式,服务器必须发送数据数组。当服务器流传输数据时,客户端可以发送停止请求来停止流传输。如果请求和响应在同一个 TCP 连接上传输,则服务器仅在所有数据完成流式传输到客户端时才收到停止请求。我想我必须使用异步写入来解决这个问题。这是我的代码:

首先,我创建一个循环以接收来自客户端的连接:

while (!done)
{
       try
       {
          Socket socket = listener.AcceptSocket();
          ClientInteraction clIr = new ClientInteraction(socket, statusList);
          Thread thread = new Thread(new ThreadStart(clIr.Process));
          thread.Start();                                     
        }
        catch (Exception ex)
         {
               Console.WriteLine(ex.ToString());
         }
       }
}

ClientInteraction 类的 Process 函数:

Public void Process()
{
            ns = new NetworkStream(socket);
            while (true)
            {
                try
                {

                        this.myReadBuffer = new byte[socket.ReceiveBufferSize];
                        this.numberOfBytesRead = ns.Read(myReadBuffer, 0, myReadBuffer.Length);

                }
                catch
                {
                    break;
                }
                if (numberOfBytesRead == 0)
                {
                    break;
                }
                else
                {

                    HandleRequest(myReadBuffer, numberOfBytesRead);

                }
            }
}

在 HandleRequest 函数中,如果请求是 STREAM,我会将数组中的数据发送到客户端:

Public void HanldeRequest(……)
{
    myCompleteMessage = "";
    myCompleteMessage =
               String.Concat(myCompleteMessage, Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));
    If(myCompleteMessage == “Stream”)
    {
        //I get data and call SendData function
            foreach(.......)
            {
              //get data
              ........
            SendData(data);
            }
    }
}        
   public void SendData(byte[] data)
        {
            try
            {
                //ns.Write(data, 0, data.Length);
                ns.BeginWrite(data, 0, data.Length, new AsyncCallback(StreamData), null);
            }
            catch
            {

            }
        }

        public void StreamData(IAsyncResult asynResult)
        {
            if(asynResult != null)
                ns.EndWrite(asynResult);
        }

使用此代码,我与客户端连接,发送数据给客户端。但在所有数据传输完毕之前,我仍然无法收到停止请求。请告诉我解决问题的正确方法。谢谢。

I have built a server that receives requests from a client and gives a response that depends on the request Type. If the request type is streaming, the server must send data array. While the server’s streaming data the client may send a stop request to stop the streaming. If the request and the response is transferred on the same TCP connection the server only receives the stop request when all the data has finished streaming to the client. I think I must use Asynchronous write to solve this problem. This is my code:

First I create a loop back to receive connection from clients:

while (!done)
{
       try
       {
          Socket socket = listener.AcceptSocket();
          ClientInteraction clIr = new ClientInteraction(socket, statusList);
          Thread thread = new Thread(new ThreadStart(clIr.Process));
          thread.Start();                                     
        }
        catch (Exception ex)
         {
               Console.WriteLine(ex.ToString());
         }
       }
}

In Process function of ClientInteraction class :

Public void Process()
{
            ns = new NetworkStream(socket);
            while (true)
            {
                try
                {

                        this.myReadBuffer = new byte[socket.ReceiveBufferSize];
                        this.numberOfBytesRead = ns.Read(myReadBuffer, 0, myReadBuffer.Length);

                }
                catch
                {
                    break;
                }
                if (numberOfBytesRead == 0)
                {
                    break;
                }
                else
                {

                    HandleRequest(myReadBuffer, numberOfBytesRead);

                }
            }
}

In HandleRequest Function, if request’s STREAM, I will send data in an array to client:

Public void HanldeRequest(……)
{
    myCompleteMessage = "";
    myCompleteMessage =
               String.Concat(myCompleteMessage, Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));
    If(myCompleteMessage == “Stream”)
    {
        //I get data and call SendData function
            foreach(.......)
            {
              //get data
              ........
            SendData(data);
            }
    }
}        
   public void SendData(byte[] data)
        {
            try
            {
                //ns.Write(data, 0, data.Length);
                ns.BeginWrite(data, 0, data.Length, new AsyncCallback(StreamData), null);
            }
            catch
            {

            }
        }

        public void StreamData(IAsyncResult asynResult)
        {
            if(asynResult != null)
                ns.EndWrite(asynResult);
        }

With this code, I connected with client, send data to client. But I still can’t receive Stop request until all data is streamed. Please show me the correct way to fix my problem. Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你爱我像她 2024-12-07 11:01:19

我认为你可以尝试使用多线程来解决这个问题。我就遇到过这种情况,多线程是解决这个问题的一个不错的选择。您可以创建一个用于写入的线程和一个用于读取的线程。

I think you can try using multithread to solve this problem. I have met this circumstance and multithread is a good choice to solve. You can create a thread to write and a thread to read.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文