c#TCP NetworkStream未接收数据

时间:2016-02-16 05:16:10

标签: c#

我正在尝试通过TCP连接发送文件后发送文件。在接收方主机的末尾,接收数据包。我使用Wireshark来确认它。但是,无法在NetworkStream中收到数据。

public class FileTransporter
{
    public void ReceiveFiles(IPAddress IP, int port)
    {
        TcpListener tcpListener = new TcpListener(IP, port);
        tcpListener.Start();
        using (TcpClient tcpClient = tcpListener.AcceptTcpClient())
        {
            if (tcpClient.Connected)
            {
                using (NetworkStream networkStream = tcpClient.GetStream())
                {
                    int pointer = 0;
                    byte[] fileNameLengthBytes = new byte[sizeof(int)];
                    networkStream.Read(fileNameLengthBytes, pointer, fileNameLengthBytes.Length);
                    int fileNameLength = BitConverter.ToInt32(fileNameLengthBytes, pointer);

                    // code to read fileName and it's size

                    networkStream.Close();
                }
            }
            tcpClient.Close();
        }
        tcpListener.Stop();
    }

    public void SendFiles(IPAddress IP, int port, string[] paths)
    {
        for(int i=0; i<paths.Length; i++)
        {
            FilePackage filePackage = new FilePackage(paths[i]);
            byte[] infoBytes = filePackage.EncodeInfoToByte();
            using (TcpClient tcpClient = new TcpClient())
            {
                tcpClient.Connect(IP, port);
                using (NetworkStream networkStream = tcpClient.GetStream())
                {
                    networkStream.Write(infoBytes, 0, infoBytes.Length);
                    networkStream.Close();
                }
                tcpClient.Close();
            }
        }
    }
}

public class FilePackage
{
    public FilePackage(string fileName)
    {
        this.Info = new FileInfo(fileName);
    }

    public byte[] EncodeInfoToByte()
    {
        List<byte> infoByte = new List<byte>();

        infoByte.AddRange(BitConverter.GetBytes(this.Info.Name.Length));
        infoByte.AddRange(Encoding.UTF8.GetBytes(this.Info.Name));

        infoByte.AddRange(BitConverter.GetBytes(this.Info.Length));

        return infoByte.ToArray();
    }

2 个答案:

答案 0 :(得分:0)

我将假设以某种方式/在其他地方调用ReadFiles。

我有一个非常类似的实现,但是我的&#34; Read&#34;流的数量要小得多:

// Read the first batch of the TcpServer response bytes.
            var bytes = new byte[512];
            // Loop to receive all the data sent by the Server.
            var sb = new StringBuilder();
            do
            {
                var i = stream.Read(bytes, 0, bytes.Length);
                sb.AppendFormat("{0}", Encoding.ASCII.GetString(bytes, 0, i));
            } while (stream.DataAvailable);

也许正在使用&#34; stream.DataAvailable&#34;将允许您测试数据是否存在,这样您就可以确保只在数据可用时进行处理。

我也不知道&#34;指针&#34;正在您的代码中初始化。 如果每次都没有设置为0,则不会从数据包的开头进行处理。

答案 1 :(得分:0)

您的问题可能是由nagle算法引起的,可以防止发送少量数据以减少拥塞。您可以尝试通过在tcpClient

上设置以下属性来禁用它

tcpClient.NoDelay = true; tcpClient.Client.NoDelay = true

相关问题