如何通过tcp套接字发送和接收文件

问题描述 投票:0回答:1

现在我知道这个问题已经被问了很多,但我真的不知道该怎么做。我尝试了这个,但是文件没有完成我只收到了文件的一部分,其余部分只是 NULL 这是我在客户端部分的代码我首先向服务器发送一条消息,其中包含如下文件大小:

// here I send the a upload request with the size of the file that I want to send
byte[] data = Encoding.Unicode.GetBytes("uploadreq~"+new FileInfo(ofg.FileName).Length);
// here is the socket client    
target.Send(data);

然后在服务器端:

if (cmd.Contains(update.update_request))
{
    // here I set an int var to the file size
    update.update_size = int.Parse(cmd.Split('~')[1]);

    // here I setup the a new byte array with the given file size
    update.update_received = new byte[update.update_size];

    // then I send a upload confirm command 
    Connection.sendCommand(Commands.update_confirme);
    update.isupdate = true;
}

收到确认后再次在客户端:

if (cmd.StartsWith("updateConfirm"))
{
    // reading all the bytes of the file and sending them
    byte[] datatosend = File.ReadAllBytes("the file path");
    Connection.send_bytes(datatosend);
}

终于在客户端了:

private void receiveInfo()
{
    byte[] buffer = new byte[999999];
    int received = 0;

    try
    {
        received =  Connection.clientSocket.Receive(buffer);
    }
    catch (SocketException)
    {
        Connection.clientSocket.Close();
        Connection.clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        Connection.makeConnection();
    }

    if (received == 0)
        return;

    byte[] data = new byte[received];
    Array.Copy(buffer, data, received);
       
    if (update.isupdate == true)
    {
         // this calls a method that process the data received 
         update.process_update(data);
    }
}

public static void process_update(byte[] data)
{
    int writeSize = 0;
    Buffer.BlockCopy(data, 0, update_received, writeSize, data.Length);
    writeSize += data.Length;

    if (update_received.Length == update_size)
    {
        using (FileStream fs = File.Create("the path to where the file shloud go"))
        {
            byte[] info = update_received;
            fs.Write(info, 0, info.Length);
        }

        Array.Clear(update_received, 0, update_received.Length);
      
        isupdate = false;
    }
}

当我写这个问题时,我更改了接收信息方法中的缓冲区大小,这似乎改变了一些内容,但文件仍然无法完全到达..

c# sockets buffer sendfile
1个回答
4
投票

为客户尝试一下:

private void SendFile(String FileName,String IPAddress,int  Port )
{
        System.Net.Sockets.TcpClient TcpClient = new System.Net.Sockets.TcpClient(IPAddress, Port);
        System.Net.Sockets.NetworkStream NetworkStream = TcpClient.GetStream();
        System.IO.Stream FileStream = System.IO.File.OpenRead(FileName);
        byte[] FileBuffer = new byte[FileStream.Length];
        
        FileStream.Read(FileBuffer, 0, (int)FileStream.Length);
        NetworkStream.Write(FileBuffer, 0, FileBuffer.GetLength(0));
        NetworkStream.Close();
}

这是服务器的代码:

private void ReceiveFile(String FilePath, int Port)
    {
        System.Threading.Thread WorkerThread = new System.Threading.Thread(() =>
        {
            System.Net.Sockets.TcpListener TcpListener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, Port);
            TcpListener.Start();
            System.Net.Sockets.Socket HandlerSocket = TcpListener.AcceptSocket();
            System.Net.Sockets.NetworkStream NetworkStream = new System.Net.Sockets.NetworkStream(HandlerSocket);
            int BlockSize = 1024;
            int DataRead = 0;
            Byte[] DataByte = new Byte[BlockSize];
            lock (this)
            {
                System.IO.Stream FileStream = System.IO.File.OpenWrite(FilePath);

                while (true)
                {
                    DataRead = NetworkStream.Read(DataByte, 0, BlockSize);
                    FileStream.Write(DataByte, 0, DataRead);
                    if (DataRead == 0)
                    {
                        break;
                    }
                }
                FileStream.Close();
            }
        });
        WorkerThread.Start();
    }

这只会传输一个文件。

© www.soinside.com 2019 - 2024. All rights reserved.