使用套接字接收文件时出现问题 - C# [英] Problem in receving file with socket - C#

查看:111
本文介绍了使用套接字接收文件时出现问题 - C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正试图通过套接字从服务器发送文件到客户端(即时使用反向连接方法)

所以这是我的步骤:

0 - 向客户发送上传请求

1 - 阅读文件长度+文件名

2 - 向客户发送详细信息

3客户端将创建一个具有计算长度的字节数组

3从服务器读取文件到字节数组

4-send byte with socket.send(byte,0 ,byte.lenght,socketflag.none)



但问题是当我从客户端收到文件已收到时,我的文件坏了。

我该如何解决这个问题?



我的尝试:



ReceiveInfo()方法用于客户端

 static private void ReceiveInfo()//客户端接收数据检查它是否是正常命令或下载请求file 
{
byte [] buffer = new byte [1024];
int received = 0;

try
{
received = ClientSocket.Receive(buffer);
}
catch(SocketException)
{
//
}

如果(收到== 0)
返回;

byte [] data = new byte [received];
System.Array.Copy(缓冲区,数据,已收到);

if(IsDownload)
{
DownloadCommand(data);
}

其他
{
NormalCommand(数据);
}

}





当我发送上传请求时,IsDownload的旗帜会改变真实。

以下是第3步:(当客户收到下载请求时)

 string [] info = //它包含详细信息file 
FileName = info [1];
FileSize = int.Parse(info [2]);
FileBytes = new byte [FileSize];
IsDownload = true;





客户端收到信息,创建字节数组并等待服务器发送数据。 />


 public static void DownloadCommand(byte [] data)
{


Buffer.BlockCopy (data,0,FileBytes,WriteSize,data.Length);

WriteSize + = data.Length;


if(FileBytes.Length == FileSize)
{
try
{
using(FileStream fs = File.Create(FileName) ))
{
byte [] info = FileBytes;
fs.Write(info,0,info.Length);
}

Array.Clear(FileBytes,0,FileBytes.Length);
}
catch(exception ex)
{

}
SendData(File Received。);
IsDownload = false;
WriteSize = 0;
}
}





这是服务器代码:



 public static void SendFile(Socket s,string fileName)
{
try
{
if(s.Connected)
{
TargetClient = s;
byte [] dataToSend = File.ReadAllBytes(fileName);
string fileInfo = Path.GetFileName(fileName)+〜+ dataToSend.Length;
SendCommand(IsDownload~+ fileInfo);
TargetClient.Send(dataToSend,0,dataToSend.Length,SocketFlags.None);
}

}

catch(exception ex)
{
LogManager.SetLog(SendFile中的错误(套接字,字符串): \ n+ ex.Message);
};

}

解决方案

你在接收函数中缺少一个循环,这意味着你只收到第一个一个文件的1024个字节。

请参见此处的示例:套接字发送和接收[C#] [ ^ ]

和此处:使用C#中的套接字 [ ^ ]

另一种方法是使用 WebClient(),这样可以简单得多: [ https://www.dotnetperls.com/webclient ]

Hi,
I'm trying to send a file over socket from server to client ( im using Reverse Connection method )
So here is my steps:
0-send a upload request to client
1-reading file lenght + filename
2-send details to client
3-client will create a byte array with the calculated length
3-reading file from server into byte array
4-send byte with socket.send(byte,0,byte.lenght,socketflag.none)

But the problem is when i receive the "File Received" from the client, my file is broken.
How can i fix this?

What I have tried:

The ReceiveInfo() method is for client-side

static private void ReceiveInfo() //Client receving data check if its a normal command or request to download a file
            {
                byte[] buffer = new byte[1024];
                int received = 0;

                try
                {
                    received = ClientSocket.Receive(buffer);
                }
                catch (SocketException)
                {
                    //
                }

                if (received == 0)
                    return;

                byte[] data = new byte[received];
                System.Array.Copy(buffer, data, received);

                if(IsDownload)
                {
                    DownloadCommand(data);
                }

                else
                {
                    NormalCommand(data);
                }

            }



when i send the upload request,the flag of IsDownload will change to true.
Here is the step 3: (when client recevies the download request)

string[] info = // it contains details of file
FileName = info[1];
FileSize = int.Parse(info[2]);
FileBytes = new byte[FileSize];
IsDownload = true;



Client receives the info,create byte array and waiting for server to send the data.

public static void DownloadCommand(byte[] data)
            {


                    Buffer.BlockCopy(data, 0, FileBytes, WriteSize, data.Length);

                    WriteSize += data.Length;


                if (FileBytes.Length == FileSize)
                {
                    try
                    {
                        using (FileStream fs = File.Create(FileName))
                        {
                            byte[] info = FileBytes;
                            fs.Write(info, 0, info.Length);
                        }

                        Array.Clear(FileBytes, 0, FileBytes.Length);
                    }
                    catch (Exception ex)
                    {

                    }
                    SendData("File Received.");
                    IsDownload = false;
                    WriteSize = 0;
                }
            }



And here is the server codes:

public static void SendFile(Socket s, string fileName)
            {
                try
                {
                    if (s.Connected)
                    {
                        TargetClient = s;
                        byte[] dataToSend = File.ReadAllBytes(fileName);
                        string fileInfo = Path.GetFileName(fileName) + "~" + dataToSend.Length;
                        SendCommand("IsDownload~" + fileInfo);
                        TargetClient.Send(dataToSend,0,dataToSend.Length,SocketFlags.None);
                    }

                }

                catch (Exception ex)
                {
                    LogManager.SetLog("Error in SendFile(Socket,string):\n" + ex.Message);
                };

            }

解决方案

You are missing a loop in your receive function, this means you only receive the first 1024 bytes of a file.
See example here: Socket Send and Receive [C#][^]
and here: Working with Sockets in C#[^]
An alternative is using WebClient(), which makes things a lot simpler: [https://www.dotnetperls.com/webclient]


这篇关于使用套接字接收文件时出现问题 - C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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