在TCP侦听器中从网络流中读取数据

时间:2013-10-11 11:00:48

标签: c#

我有一个网络流,里面有文件名和filedata。我正在以一些块发送文件,每个块都带有文件名以便于识别。能否帮我正确读取网络流并将所有数据写入文件流。 当我从网络流中写入数据时,我似乎错过了几个字节。 比方说,文件名长度将在索引中,文件名将从第4个索引开始。

    Client:

    int NoOfPackets = Convert.ToInt32
          (Math.Ceiling((Convert.ToDouble(Fs.Length))/ Convert.ToDouble(BufferSize)));
           int TotalLength = (NoOfPackets *4+fileNameByte.Length) +(int)Fs.Length,     CurrentPacketLength, counter = 0;
        netstream1 = client.GetStream();
          for (int i = 0; i < NoOfPackets+1 ; i++)
          {

              if (TotalLength > BufferSize)
              {
                  CurrentPacketLength = BufferSize;
                  TotalLength = TotalLength - CurrentPacketLength;
              }
              else
                  CurrentPacketLength = TotalLength;
              SendingBuffer = new byte[CurrentPacketLength];
             fileNameLength.CopyTo(SendingBuffer, 0);
              fileNameByte.CopyTo(SendingBuffer, 4);
              Fs.Read(SendingBuffer, 4 + fileNameByte.Length, CurrentPacketLength - (4 + fileNameByte.Length));
             netstream1.Write(SendingBuffer, 0, SendingBuffer.Length);
               netstream1.Flush();
                 }

听众代码:

           client = Listener.AcceptTcpClient();
                    client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
                    //client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, true);
                    client.Client.LingerState = new LingerOption(true, 300);
                    client.Client.SendTimeout = 300000;                     
                    client.Client.ReceiveTimeout = 300000;
                    client.NoDelay = true;
                    NetworkStream netstream = client.GetStream();

                    MemoryStream ms = new MemoryStream();
                    bool first = true;
                    string fullPath = "";
                    byte[] RecData = new byte[512000];

                    while ((RecBytes = netstream.Read
                        (RecData, 0, RecData.Length)) > 0)
                    {

                        int fileNameLen = RecData[0];

                        if (fileNameLen > 0 && first)
                        {
                            string name1 = "", name2 = "";
                            first = false;

                            name1 = Encoding.UTF8.GetString(RecData, 4, fileNameLen);


                            name2 = name1;

                            string folderName = "";
                            if (name2.Contains("\\"))
                            {
                                folderName = name2.Substring(0, name2.LastIndexOf("\\"));
                                if (!Directory.Exists("D:\\123\\" + folderName))
                                    Directory.CreateDirectory("D:\\123\\" + folderName);

                            }
                            if (folderName != "")
                                fullPath = "D:\\123\\" + folderName + "\\" + name2.Substring(name2.LastIndexOf("\\") + 1);
                            else
                                fullPath = "D:\\123\\" + name2.Substring(name2.LastIndexOf("\\") + 1);
                        }


                        if (!File.Exists(fullPath))
                        {

                            //file = new FileStream(fullPath, FileMode.OpenOrCreate, FileAccess.Write);

                            while (true)
                            {
                                try
                                {
                                    using (FileStream file = new FileStream(fullPath, FileMode.OpenOrCreate, FileAccess.Write))
                                    {

                                        if (RecBytes - (4 + fileNameLen) > 0)
                                            file.Write(RecData, 4 + fileNameLen, RecBytes - (4 + fileNameLen));
                                        break;
                                    }
                                }
                                catch (IOException)
                                {

                                    Thread.Sleep(20);
                                }
                            }
                            //using (file = File.Create(fullPath))
                            //{
                            //    file.Write(data, 4 + fileNameLen, (int)data.Length - (4 + fileNameLen));
                            //}


                        }
                        else
                        {

                            while (true)
                            {
                                try
                                {
                                    using (FileStream file = new FileStream(fullPath, FileMode.Append, FileAccess.Write))
                                    {

                                        if (RecBytes - (4 + fileNameLen) > 0)
                                            file.Write(RecData, 4 + fileNameLen, RecBytes - (4 + fileNameLen));
                                        break;
                                    }
                                }
                                catch (IOException)
                                {

                                    Thread.Sleep(20);
                                }
                            }

                        }


                    }

                    ms.Close();

                    netstream.Close();
                    client.Close();

1 个答案:

答案 0 :(得分:0)

即使你像任何人一样模糊,我仍然建议你创建一个结构,以便可以以已知的格式完成数据的序列化和反序列化!并且可以避免数据丢失!! 如果您的方法已知,那么回答您的问题将会非常有帮助。