C#Socket发送图片JPEG

时间:2013-02-13 21:59:46

标签: c# sockets jpeg mirc

所以我在stackoverflow中找到了一个代码,用于通过套接字发送一个二进制文件,一个图像..所以我用它来测试我的项目

private void send_ss()
    {
        byte[] data = new byte[1024];
        int sent;
        IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 306);

        Socket server = new Socket(AddressFamily.InterNetwork,
                        SocketType.Stream, ProtocolType.Tcp);

        try
        {
            server.Connect(ipep);
        }
        catch (SocketException e)
        {
            //Console.WriteLine("Unable to connect to server.");
            //Console.WriteLine(e.ToString());
            //Console.ReadLine();
        }


        Bitmap bmp = new Bitmap("C:\\Windows\\Web\\Wallpaper\\Theme2\\img7.jpg");

        MemoryStream ms = new MemoryStream();
        // Save to memory using the Jpeg format
        bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

        // read to end
        byte[] bmpBytes = ms.ToArray();
        bmp.Dispose();
        ms.Close();

        sent = SendVarData(server, bmpBytes);

        //Console.WriteLine("Disconnecting from server...");
        server.Shutdown(SocketShutdown.Both);
        server.Close();
    }
    private static int SendVarData(Socket s, byte[] data)
    {
        int total = 0;
        int size = data.Length;
        int dataleft = size;
        int sent;

        byte[] datasize = new byte[4];
        datasize = BitConverter.GetBytes(size);
        sent = s.Send(datasize);

        while (total < size)
        {
            sent = s.Send(data, total, dataleft, SocketFlags.None);
            total += sent;
            dataleft -= sent;
        }
        return total;
    }

所以我试图将这张照片发送到我在306端口的侦听套接字上(用m IRC听)

on *:socklisten:ac_img:{
  var %p = $ticks $+ $time(hhnnss) $+ $ctime
  sockaccept ac_img_ $+ %p
  echo -s [] Image Connection Established On -> ac_img_ $+ %p
}
on *:sockread:ac_img_*:{
  sockread &picture 
  bwrite $qt($mIRCdir $+ $sockname $+ .jpg) -1 -1 &picture 
}

所以我得到的文件有ac_img_2920385501147471360792067.jpg等等。与原始尺寸相同但是图像没有出现,所以我用字垫打开了两个文件,它们有点不同......不知道为什么... ScreenShot

所以我想面对这个问题的任何想法?我的意思是......我从我的套接字中获取每个数据并将它们保存到文件中?也许通过c#读取文件损坏?

1 个答案:

答案 0 :(得分:2)

图像不同,因为您阅读它,将其解析为Bitmap并重新编码。 wordpad屏幕截图显示两者都是JPEG,但具有不同的元数据(例如“adobe”缺失“)。

只需使用File.ReadAllBytes或其他无损方法即可读取图像。

发送代码看起来很合理。不知道你为什么要循环。发送永远不会阻止套接字上的部分IO AFAIK。