简体   繁体   English

C#与NetworkStream异步读写

[英]C# Asynchronous read and write with NetworkStream

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. 如果请求和响应是在同一TCP连接上传输的,则服务器仅在所有数据完成向客户端的流传输时才接收停止请求。 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 : ClientInteraction类的In 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);

                }
            }
}

In HandleRequest Function, if request's STREAM, I will send data in an array to client: 在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);
        }

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. 谢谢。

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. 您可以创建要写入的线程和要读取的线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM