简体   繁体   中英

Error in asynchronous read from the NetworkStream

I have make an application to communicate with an IP Camera. That is configured to make connection on a predefined address. And TCP Listener is running on that address and accepts connection from camera. When camera connects i send command to get MJpeg stream from camera and camera starts sending stream in response to command.

I am using asynchronous method to read stream from socket. But after sometime my application is stuck while reading data from network stream.

I am using this code to read Data from network stream and i have write some messages on the screen to get status of camera connection.

    private void ReadData()
    {
        try
        {
            string msg = "Reading Data... client connected " + _camClient.Connected.ToString() +
                         "... netStream Readable " +
                         _netStream.CanRead.ToString();
            Console.WriteLine(msg);

            _callback = new AsyncCallback(GetData);
            _buffer = new byte[Buffersize];
            _async = _netStream.BeginRead(_buffer, 0, Buffersize, _callback, null);
        }
        catch (Exception ex) { Console.WriteLine("ReadData: " + ex.Message); }
    }

    private void GetData(IAsyncResult result)
    {
        try
        {
            int read = _netStream.EndRead(result);
            if (read > 0)
            {
                _data = new byte[read];
                Array.Copy(_buffer, 0, _data, 0, read);
                ProcessData();
            }
            ReadData();
        }
        catch (Exception ex) { Console.WriteLine("GetData: " + ex.Message); }
    }

Firstly asynchronous methods on network streams are well known for loosing data or for never returning data! In your case it could be the ProcessData call is blocking.

What you should do is to spawn a new background thread with a blocking listener (non asynchronous) and then use a new thread to read the data while the listener continues to listen. I have an example here.

private static Socket s_chatListener;
public static void Listen(IPAddress LocalIPAddress, int Port)
    {
            IPEndPoint ipend = new IPEndPoint(LocalIPAddress, Port);
            s_chatListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            s_chatListener.Bind(ipend);
            s_chatListener.Listen(10);


            while (true)
            {
                Socket handler = s_chatListener.Accept();

                ParameterizedThreadStart pst = new ParameterizedThreadStart(loadMessageFromSocket);
                Thread t = new Thread(pst);
                t.Start(handler);


            }
    }


 private static  void loadMessageFromSocket(object socket)
    {
        Socket handler = (Socket)socket;
        string data = "";
        while (true)
        {
            byte[] butes = new byte[1024];
            int rec = handler.Receive(butes);

            data += ASCIIEncoding.ASCII.GetString(butes);

            if (data.IndexOf("\0") > -1)
                break;
        }

        handler.Shutdown(SocketShutdown.Both);
        handler.Close();


        Console.Write(data);
    }

Now just call the Listen Method from a new Thread in your main form or caller class. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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