网络流不读取最后8192个字节的数据,跳出while循环 [英] Network stream is not reading the last 8192 bytes of data, tripping out of the while loop

查看:63
本文介绍了网络流不读取最后8192个字节的数据,跳出while循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读取大约3824726字节的大字节。我已经尝试了很多函数来读取整个字节。它正好读取3816534个字节,而while循环正在消失一些地方。剩余的8192个字节未被读取,也没有异常。它读到正好是3816534然后当打开时while循环消失了。请一些人帮忙,告诉我这里可能存在什么问题。我已经尝试了很多,但同样的事情正在发生在不同的功能中。

I'm reading a huge byte of around 3824726 bytes. I've tried a lot of functions for reading the whole bytes. It is reading exactly 3816534 bytes and the while loop is going away some where. Remaining 8192 bytes are not being read and also there is no exception. It reads till exactly 3816534 and then when on while loop goes away somewhere. Please some one help and tell what may be the problem here. I have tried a lot but the same thing is happening in different functions.

public static void ReadFully(NetworkStream stream, int initialLength)
    {
        if (initialLength < 1)
        {
            initialLength = 32768;
        }

        byte[] buffer = new byte[initialLength];
        int chunk;
        try
        {
            int read = -1;
            int totread = 0;

            while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
            {
                totread += read;
                Console.WriteLine("Toatal Read" + totread);
                string filePath = "C:\\Foo.txt";
                StreamWriter objWriter;
                using (objWriter = File.AppendText(filePath))
                {
                    objWriter.WriteLine(totread);
                    objWriter.Flush();
                    objWriter.Close();
                }
            }
            Console.WriteLine("Toatal Read" + totread);
        }
        catch (Exception ex)
        { throw ex; }
    }



客户端向服务器发送字节


Client Side Sending bytes to server

byte[] fileA;


        IPAddress ipAd = IPAddress.Parse("IpAddress");
        TcpClient client = new TcpClient(ipAd.ToString(), Port);
        NetworkStream stream = client.GetStream();

        StreamReader reader = new StreamReader("D:/Users/Public/Pictures/Sample        Pictures/06250_2.jpg");
        //StreamReader reader = new StreamReader("D:/Users/703132799/Desktop/Foo.txt");
        string data = reader.ReadToEnd();
        reader.Close();
        fileA = System.Text.Encoding.ASCII.GetBytes(data);
        int length = 0;
        length = fileA.Length;
        Console.WriteLine("Sending Buffer Length-" + length);
        stream.Write(fileA, 0, fileA.Length);
        stream.Flush();
        //Thread.Sleep(10000);
        Console.ReadLine();



服务器上的整个代码,它是异步方式


Whole code at server, It is Asynchronous way

static void Main(string[] args)
    {
        StartServer();
    }

    private static TcpListener _listener;
    public static void StartServer()
    {

        IPAddress localIPAddress = IPAddress.Parse("IPAddress");
        IPEndPoint ipLocal = new IPEndPoint(localIPAddress, Port);
        _listener = new TcpListener(ipLocal);
        _listener.Start();
        WaitForClientConnect();
    }

    private static void WaitForClientConnect()
    {
        object obj = new object();
        _listener.BeginAcceptTcpClient(new System.AsyncCallback(OnClientConnect), obj);
        Console.ReadLine();
    }

    private static void OnClientConnect(IAsyncResult asyn)
    {
        try
        {
            TcpClient clientSocket = default(TcpClient);
            clientSocket = _listener.EndAcceptTcpClient(asyn);
            HandleClientRequest clientReq = new HandleClientRequest(clientSocket);
            clientReq.StartClient();
        }
        catch (Exception ex)
        {
            throw ex;
        }

        WaitForClientConnect();
    }
}

public class HandleClientRequest
{
    TcpClient _clientSocket;
    NetworkStream _networkStream = null;

    public HandleClientRequest(TcpClient clientConnected)
    {
        this._clientSocket = clientConnected;
    }

    public void StartClient()
    {
        _networkStream = _clientSocket.GetStream();
        WaitForRequest();
    }

    public void WaitForRequest()
    {
        byte[] buffer = new byte[_clientSocket.ReceiveBufferSize];

        _networkStream.BeginRead(buffer, 0, buffer.Length, ReadCallback, buffer);
    }

    private void ReadCallback(IAsyncResult result)
    {
        string sRecMsgAsciiWithHex = string.Empty;
        NetworkStream networkStream = _clientSocket.GetStream();
        ReadFully(networkStream, 65536);
    }

    public static void ReadFully(NetworkStream stream, int initialLength)
    {
        if (initialLength < 1)
        {
            initialLength = 32768;
        }

        byte[] buffer = new byte[initialLength];
        int chunk;
        try
        {
            int read = -1;
            int totread = 0;
            using (var fileStream = File.OpenWrite("C:\\Foo.txt"))
            {

                while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    totread += read;
                    Console.WriteLine("Toatal Read" + totread);
                    fileStream.Write(buffer, 0, buffer.Length);
                    //string filePath = "C:\\Foo.txt";
                    //StreamWriter objWriter;
                    //using (objWriter = File.AppendText(filePath))
                    //{
                    //    objWriter.WriteLine(totread);
                    //    objWriter.Flush();
                    //    objWriter.Close();
                    //}
                }
            }
            Console.WriteLine("Toatal Read" + totread);
        }
        catch (IOException e)
        { throw; }
    }

推荐答案



请记住,服务器有不知道发送了多少数据。并且,如果客户端在发送最后一条消息之后但在服务器已读取最后一条消息之前断开连接,则连接将丢失,并且看起来您丢失了数据。


Remember, the server has no idea how much data is being sent. And, if the client disconnects after sending the last message but before the server has read the last message, the connection will be lost and it will appear that you have lost data.



这里有一个关于你能做什么的想法:


Here's a thought on what you can do:



  • 使用同步客户端/服务器。

  • 设置消息协议:



    • 让客户端发送总字节数消息,例如

      < TOTAL>总数-of-bytes-to-sent< / TOTAL>

    • 等待服务器响应包含total-number-of-bytes-to-的消息被发送。这表示服务器已准备好接收字节。

    • 当服务器响应时,开始一次读取输入文件,例如1024字节。在数据消息中封装数据的每个块,例如:

      < DATA>数据块< / DATA>

      并将数据发送到服务器。您无需等待服务器。

    • 发送完最后一块数据后,即使它只是部分消息,也要发送已完成的消息

      < FINISHED>要发送的总字节数< / FINISHED>

    • 等待服务器响应带有包含要发送的总字节数的消息。这表示服务器收到了所有字节。

    • 现在您可以关闭客户端的连接。



    你几乎无法控制缓冲区的大小,所以你可能需要确保在消息中正确识别出两个或多个数据缓冲区。


    You have very little control over the size of the buffers, so you may need to insure that two or more data buffers are properly identified in a message.



    我可以提供使用这种方法的代码。


    I can supply code that uses this method.



    希望有所帮助。


    Hope that helps.


    这篇关于网络流不读取最后8192个字节的数据,跳出while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆