通过套接字发送数据不完整

本文关键字:数据 套接字 | 更新日期: 2023-09-27 18:30:22

对于我的项目,我正在尝试在客户端中截取屏幕截图并通过套接字将它们发送到服务器。我使用循环截取屏幕截图,直到手动停止。但是,虽然截图很好,但是发送后,一些图像只占主图像的一半,有些图像已满。
客户:
我正在用这个
截图

bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
gfxScreenshot = Graphics.FromImage(bmpScreenshot);
gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
bmpScreenshot.Save(path + i + ".png");
ClientService.SendFile(path + i + ".png");
i++;

并且发送文件方法是

public static void SendFile(string fileName)
        {
            try
            {
                IPAddress[] ipAddress = Dns.GetHostAddresses("localhost");
                IPEndPoint ipEnd = new IPEndPoint(ipAddress[0], 5656);
                Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                string filePath = "";
                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);
                if (fileNameByte.Length > 600 * 1024)
                {
                    showMsg = "File size is more than 600kb, please try with small file.";
                    return;
                }
                byte[] fileData = File.ReadAllBytes(filePath + fileName);
                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);
                clientSock.Connect(ipEnd);
                clientSock.Send(clientData);
                clientSock.Close();
            }
            catch (Exception ex)
            {
                if (ex.Message == "No connection could be made because the target machine actively refused it")
                    showMsg = "File Sending fail. Because server is not running.";
                else
                    showMsg = "File Sending fail." + ex.Message;
            }
        }

服务器

IPEndPoint ipEnd;
    Socket sock;
    public ServerService()
    {
        ipEnd = new IPEndPoint(IPAddress.Any, 5656);
        sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
        sock.Bind(ipEnd);
    }
    public static string receivedPath;
    internal void StartServer()
    {
        try
        {
            sock.Listen(100);
            Socket clientSock = sock.Accept();
            byte[] clientData = new byte[1024 * 5000];
            int receivedBytesLen = clientSock.Receive(clientData);
            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);
            bWrite.Close();
            clientSock.Close();
        }
        catch (Exception ex)
        {
            ShowMsg = "Something is wrong." + ex.Message;
        }
    }

如何解决这个问题?

通过套接字发送数据不完整

Receive 只能保证(其中之一):

  • 返回至少 1 个字节
  • 发出 EOF 信号(非正字节)
  • 发出错误信号

仅仅给Receive打电话一次是不够的。您需要在循环中调用它,直到:

  • 您已经阅读了所需的所有数据
  • 你得到一个EOF
  • 您收到错误

在您的情况下,我建议您:

  • 准确读取 4 个字节(可能需要循环)以获取名称长度,n
  • 然后准确读取 n 个字节以读取名称
  • 然后阅读直到您获得 EOF(来自 Receive 的非阳性结果)

另外:您可能希望使用基于 Stream 的 API 进行文件访问(读取和写入),而不是File.ReadAllBytesBinaryWriter

准确读取n字节的情况如下:

public void ReceiveExactly(Socket socket, byte[] buffer, int offset, int count)
{
    int read;
    while(count > 0 && (read = socket.Receive(buffer, offset, count,
        SocketFlags.None)) > 0)
    {
        offset += read;
        count -= read;
    }
    if(count != 0) throw new EndOfStreamException();
}