c# file read and send over socket

后端 未结 1 735
自闭症患者
自闭症患者 2021-01-26 07:32

This is how I send a file using a NetworkStream.

private void go()
{
    byte[] send = File.ReadAllBytes(\"example.txt\");
    ns.Write(send, 0, sen         


        
相关标签:
1条回答
  • 2021-01-26 08:20

    TCP is a stream based protocol, which means that there is no notation of application messages like in UDP. Thus you cannot really detect by TCP itself where an application message ends.

    Therefore you need to introduce some kind of detection. Typically you add a suffix (new line, semicolon or whatever) or a length header.

    In this case it's easier to add a length header since the chosen suffix could be found in the file data.

    So sending the file would look like this:

    private void SendFile(string fileName, NetworkStream ns)
    {
        var bytesToSend = File.ReadAllBytes(fileName);
        var header = BitConverter.GetBytes(bytesToSend.Length);
        ns.Write(header, 0, header.Length);
        ns.Write(bytesToSend, 0, bytesToSend.Length);
    }
    

    On the receiver side it's important that you check the return value from Read as contents can come in chunks:

    public byte[] ReadFile(NetworkStream ns)
    {
        var header = new byte[4];
        var bytesLeft = 4;
        var offset = 0;
    
        // have to repeat as messages can come in chunks
        while (bytesLeft > 0)
        {
            var bytesRead = ns.Read(header, offset, bytesLeft);
            offset += bytesRead;
            bytesLeft -= bytesRead;
        }
    
        bytesLeft = BitConverter.ToInt32(header, 0);
        offset = 0;
        var fileContents = new byte[bytesLeft];
    
        // have to repeat as messages can come in chunks
        while (bytesLeft > 0)
        {
            var bytesRead = ns.Read(fileContents, offset, bytesLeft);
            offset += bytesRead;
            bytesLeft -= bytesRead;
        }
    
        return fileContents;
    }
    
    0 讨论(0)
提交回复
热议问题