Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sockets 通过套接字在c#中传输半文件?_Sockets_C# 4.0_File Transfer_Filewriter - Fatal编程技术网

Sockets 通过套接字在c#中传输半文件?

Sockets 通过套接字在c#中传输半文件?,sockets,c#-4.0,file-transfer,filewriter,Sockets,C# 4.0,File Transfer,Filewriter,我正在通过中间层贪婪路由开发文件传输应用程序,其中文件发送到贪婪路由,贪婪路由再次将文件发送到路由器 但问题是,客户机有时会收到完整的文件,有时会收到部分文件 这是我的密码 服务器端 IPAddress[] ipAddress = Dns.GetHostAddresses("127.0.0.1"); IPEndPoint ipEnd = new IPEndPoint(ipAddress[0], 5655); Socket clientSock =

我正在通过中间层贪婪路由开发文件传输应用程序,其中文件发送到贪婪路由,贪婪路由再次将文件发送到路由器 但问题是,客户机有时会收到完整的文件,有时会收到部分文件

这是我的密码 服务器端

IPAddress[] ipAddress = Dns.GetHostAddresses("127.0.0.1");
            IPEndPoint ipEnd = new IPEndPoint(ipAddress[0], 5655);
            Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);


            string filePath = "";


            fileDes = fileDes.Replace("\\", "/");
            while (fileDes.IndexOf("/") > -1)
            {
                filePath += fileDes.Substring(0, fileDes.IndexOf("/") + 1);
                fileDes = fileDes.Substring(fileDes.IndexOf("/") + 1);
            }


            byte[] fileNameByte = Encoding.ASCII.GetBytes(fileDes);

            lblError.Text = "";
            lblError.Text = "Buffering ...";
            byte[] fileData = File.ReadAllBytes(filePath + fileDes);
            byte[] clientData = new byte[4 + fileNameByte.Length + fileData.Length];
            byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);

            fileNameLen.CopyTo(clientData, 0);
            fileNameByte.CopyTo(clientData, 4);
            fileData.CopyTo(clientData, 4 + fileNameByte.Length);

            lblError.Text = "";
            lblError.Text = "Connection to server ...";
            clientSock.Connect(ipEnd);

            lblError.Text = "";
            lblError.Text = "File sending...";
         //   System.Threading.Thread.Sleep(1000);
            clientSock.Send(clientData);
            label3.Text = clientData.Length.ToString();

            lblError.Text = "";
            lblError.Text = "Disconnecting...";
            clientSock.Close();

            lblError.Text = "";
            lblError.Text = "File transferred.";
客户

class DestCode
{
    IPEndPoint ipEnd;
    Socket sock;
    public DestCode()
    {
       ipEnd = new IPEndPoint(IPAddress.Any, 5656);
       sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
       sock.Bind(ipEnd);
    }
    public static string receivedPath;
    public static string curMsg = "Stopped";
    public static int res;
    public  void StartServer()
    {
        try
        {
            curMsg = "Starting...";
            sock.Listen(100);

            curMsg = "Running and waiting to receive file.";
            Socket clientSock = sock.Accept();

            byte[] clientData = new byte[1024 * 5000];

            int receivedBytesLen = clientSock.Receive(clientData);

            curMsg = "Receiving data...";

            int fileNameLen = BitConverter.ToInt32(clientData, 0);
            string fileName = Encoding.ASCII.GetString(clientData, 4, fileNameLen);

            BinaryWriter bWrite = new BinaryWriter(File.Open(receivedPath +"/"+ fileName, FileMode.Append)); ;
            bWrite.Write(clientData,4 + fileNameLen, receivedBytesLen - 4 - fileNameLen);
            res = receivedBytesLen;
            if (receivedPath == "")
            {
                MessageBox.Show("No Path was selected to Save the File");
            }
            curMsg = "Saving file...";

            bWrite.Close();
            clientSock.Close();
            curMsg = "File Received ...";

            StartServer();

        }
        catch (Exception ex)
        {
            curMsg = "File Receving error.";
        }
    }
}
贪婪地

class ReceiverCode
{
    IPEndPoint ipEnd;
    Socket sock;
    public ReceiverCode()
    {
        ipEnd = new IPEndPoint(IPAddress.Any, 5655);
        sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
        sock.Bind(ipEnd);
    }
    public static string receivedPath;
    public static string curMsg = "Stopped";
    public static string Rout = "";
    public static int rlength = 0;
    public static string MsgStatus = "";
    public static byte[] send;
    public void StartServer()
    {
        try
        {
            curMsg = "Starting...";
            sock.Listen(100);

            curMsg = "Running and waiting to receive file.";
            Socket clientSock = sock.Accept();

            byte[] clientData = new byte[1024 * 5000];

            int receivedBytesLen = clientSock.Receive(clientData);
           System.Threading.Thread.Sleep(5000);
            rlength = receivedBytesLen;
            curMsg = "Receiving data...";

            int receive = clientSock.Receive(clientData);


            send = new byte[receivedBytesLen];
            Array.Copy(clientData, send, receivedBytesLen);
            Rout = "Start";
            clientSock.Close();
            curMsg = "Reeived & Saved file; Server Stopped.";
            StartServer();

        }
        catch (Exception ex)
        {
            curMsg = "File Receving error.";
        }
    }


}

请有人帮帮我

问题是,
Socket.Receive
不能保证您将收到所需的所有字节。所以你写:

int receivedBytesLen = clientSock.Receive(clientData);
报告说:

如果您使用的是面向连接的套接字,Receive方法将读取尽可能多的可用数据,直到缓冲区的大小

Receive
的调用正在获取当前可用的所有字节。可能是发送方尚未发送所有字节,或者您的网络堆栈尚未接收并使其可用

要可靠地发送和接收数据,接收器必须知道两件事中的一件:它期望的字节数,或者有一个哨兵值,表示“仅此而已,伙计们。”你不能指望一个
receive
调用就能获得所有信息

传输文件时,发送方通常将文件大小作为发送数据的前四个字节。然后,代码读取前四个字节(确保获得所有四个字节)以确定大小,然后旋转一个循环,从套接字读取数据,直到收到所有预期字节

比如:

const int MaximumSize = 1000000;
// read the first four bytes
var sizeBytes = ReadBytesFromSocket(socket, 4);
int size = BitConverter.ToInt32(sizeBytes);

var dataBuffer = ReadBytesFromSocket(socket, size);
// you now have your data

byte[] ReadBytesFromSocket(Socket socket, int size)
{
    var buff = new byte[size];
    int totalBytesRead = 0;

    while (totalBytesRead < size)
    {
        int bytesRead = socket.Receive(buff, totalBytesRead, size-totalBytesRead, SocketFlags.None);
        if (bytesRead == 0)
        {
            // nothing received. The socket has been closed.
            // maybe an error.
            break;
        }
        totalBytesRead += bytesRead
    }
    return buff;
}
const int MaximumSize=1000000;
//读取前四个字节
var sizeBytes=ReadBytesFromSocket(socket,4);
int size=BitConverter.ToInt32(sizeBytes);
var-dataBuffer=ReadBytesFromSocket(socket,大小);
//你现在有你的数据了
字节[]ReadBytesFromSocket(Socket Socket,int size)
{
var buff=新字节[大小];
int totalBytesRead=0;
while(totalBytesRead
有关更多信息,请参阅我的博客文章(以及链接的第1部分和第2部分)。博客文章讨论了流,但套接字的概念是相同的