发送文件的TCP问题 [英] TCP issues with sending files

查看:45
本文介绍了发送文件的TCP问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设置了服务器,并且正在尝试将文件发送给客户端.我遇到的问题是,客户端上收到的文件有时小于或大于原始文件.

这是我正在使用的代码:

伺服器:

I have set up a server, and am trying to send a file to a client. The issue I''m having is that the file received on the client is sometimes either smaller, or bigger than the original file.

Here is the code I''m using:

Server:

class FileSendServer
    {
        Thread t1;
        byte[] clientData;

        public FileSendServer()
        {

        }

        public void letsGo()
        {
            t1 = new Thread(new ThreadStart(StartListening));
            t1.Start();
        }

        public void setFileLoc(string floc)
        {
            string filePath = "";
            string fileName = floc;
            /* File reading operation. */
            fileName = fileName.Replace("\\", "/");
            while (fileName.IndexOf("/") > -1)
            {
                filePath += fileName.Substring(0, fileName.IndexOf("/") + 1);
                fileName = fileName.Substring(fileName.IndexOf("/") + 1);
            }


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

            byte[] fileData = File.ReadAllBytes(filePath + fileName);

            /* Read & store file byte data in byte array. */
            clientData = new byte[4 + fileNameByte.Length + fileData.Length];

            /* clientData will store complete bytes which will store file name length, file name & file data. */
            byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);
            /* File name length's binary data. */
            fileNameLen.CopyTo(clientData, 0);
            fileNameByte.CopyTo(clientData, 4);
            fileData.CopyTo(clientData, 4 + fileNameByte.Length);
            /* copy these bytes to a variable with format line [file name length][file name][ file content] */
        }

        public static ManualResetEvent allDone = new ManualResetEvent(false);

        public void StartListening()
        {
            IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 9050);
            Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                listener.Bind(ipEnd);
                listener.Listen(100);
                while (true)
                {
                    allDone.Reset();
                    listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
                    allDone.WaitOne();

                }
            }
            catch (Exception ex)
            {

            }

        }
        public void AcceptCallback(IAsyncResult ar)
        {
            allDone.Set();

            Socket listener = (Socket)ar.AsyncState;
            Socket handler = listener.EndAccept(ar);

            handler.Send(clientData);

            handler.Close();
        }
    }



客户:



Client:

class FileReceiveClient
    {
        int flag = 0;
        string receivedPath = "";
        public delegate void MyDelegate();
        Form1 myForm1;

        public FileReceiveClient(Form1 x)
        {
            myForm1 = x;
            ReceiveFile();
        }

        public class StateObject
        {
            // Client socket.
            public Socket workSocket = null;

            public const int BufferSize = 1024;
            // Receive buffer.
            public byte[] buffer = new byte[BufferSize];
        }

        public void ReceiveFile()
        {
            try
            {
                IPAddress[] ipAddress = Dns.GetHostAddresses("localhost");
                IPEndPoint ipEnd = new IPEndPoint(IPAddress.Parse("192.168.1.104"), 9050);
                /* Make IP end point same as Server. */
                Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                /* Make a client socket to send data to server. */
                clientSock.Connect(ipEnd);

                StateObject state = new StateObject();
                state.workSocket = clientSock;
                clientSock.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReadCallback), state);
                flag = 0;

            }
            catch (Exception ex)
            {

            }

        }

        public void ReadCallback(IAsyncResult ar)
        {
            int fileNameLen = 1;
            String content = String.Empty;
            StateObject state = (StateObject)ar.AsyncState;
            Socket handler = state.workSocket;
            int bytesRead = handler.EndReceive(ar);
            if (bytesRead > 0)
            {

                if (flag == 0)
                {
                    fileNameLen = BitConverter.ToInt32(state.buffer, 0);
                    string fileName = Encoding.UTF8.GetString(state.buffer, 4, fileNameLen);
                    receivedPath = "C:/RBParty/Songs/" + fileName;
                    myForm1.fileLoc = receivedPath;
                    flag++;
                }

                if (flag >= 1)
                {
                    try
                    {
                        BinaryWriter writer = new BinaryWriter(File.Open(receivedPath, FileMode.Append));
                        if (flag == 1)
                        {
                            writer.Write(state.buffer, 4 + fileNameLen, bytesRead - (4 + fileNameLen));
                            flag++;
                        }
                        else
                            writer.Write(state.buffer, 0, bytesRead);
                        writer.Close();
                        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                        new AsyncCallback(ReadCallback), state);
                    }

                    catch (Exception ee)
                    {

                    }
                }

            }

            else
            {
                Thread.CurrentThread.Abort();
            }

        }
    }



任何帮助表示赞赏.预先谢谢您.



Any help is appreciated. Thank you in advance.

推荐答案

请尝试使用我的文章:^ ]
Try using my article instead : WCF Killer[^]


好,所以我创建了一个WinForms应用来测试您的代码,起初遇到了同样的问题,直到我意识到您正在调用ReceiveFile()为止;在您的FileReceiveClient类构造函数中.您看到在创建FileReceiveClient类的实例之后,我也在主窗体中调用此方法.一旦意识到这一点,我就可以毫无问题地多次运行该代码.因此,我的建议是(1)确保您不会像以前那样多次调用ReceiveFile(). (2)确保通过在文件属性对话框中查看磁盘大小和磁盘值的大小来验证文件大小(通过右键单击文件并选择属性来调出文件大小).希望你能弄清楚.
Ok so I created a WinForms app to test out your code and at first was having the same problems you are having until I realized you are calling ReceiveFile(); in your FileReceiveClient class constructor. You see I was also calling this from my main form after I created an instance of the FileReceiveClient class. Once I realized this I ran the code several more times with no problems. So my suggestions are (1) make sure you are not calling ReceiveFile() more than once like I was. (2) Make sure you are verifying the file size by looking at the size and size on disk values in the files properties dialog (bring it up by right clicking the file and choosing properties). Hope you figure it out.


这篇关于发送文件的TCP问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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