通过udp传输文件

时间:2015-03-09 20:45:10

标签: java c# sockets udp

我正在尝试通过UDP将文件从java客户端传输到c#服务器。但是,当我尝试在服务器端打开传输文件(png图片)时,它无法成功打开它。有人可以帮帮我吗?

客户端代码:(java)

import java.io.File;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


public class Program {
    public static void main(String [] args)
    {
        DatagramSocket clientSocket;
        try {
            clientSocket = new DatagramSocket();

            InetAddress IPAddress = InetAddress.getByName("192.168.1.15");
            File myFile = new File ("D:/Users/user-pc/Downloads/phone.png");
            byte [] data  = new byte[(int)myFile.length()];
            DatagramPacket sendPacket = new DatagramPacket(data, data.length, IPAddress, 3109);
            clientSocket.send(sendPacket);
            clientSocket.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

服务器代码:(c#)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] data;
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 3109);
            UdpClient newsock = new UdpClient(ipep);
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            data = newsock.Receive(ref sender);
            File.WriteAllBytes(@"d:\pics\pic.png", data);
        }
    }
}

2 个答案:

答案 0 :(得分:1)

byte [] data  = new byte[(int)myFile.length()]; 

这是你的问题,你只需初始化一个长度为myFile的新字节数组。 (不是实际数据)

Here您可以看到如何将文件转换为实际的字节[]

Files.toByteArray(File file)

答案 1 :(得分:1)

<强>第一 在发送图片之前,将其解码为base64字符串。 这里用于编码的辅助方法

public string ImageToBase64(Image image, System.Drawing.Imaging.ImageFormat format)
{
      using (MemoryStream stream = new MemoryStream())
   {
     // Convert Image to byte[]
    image.Save(stream , format);
    byte[] imageBytes = ms.ToArray();

    // Convert byte[] to Base64 String
    string base64String = Convert.ToBase64String(imageBytes);
    return base64String;
   }
}

将其编码为字节数组并发送

    byte[] data = Encoding.ASCII.GetBytes(returnedStringFromEncoder);

第二名: 从接收方:将bytes数组转换回字符串

    string data = Encoding.ASCII.GetString(recievedByteArray);

<强>最后 将其转换为图片

    public Image Base64ToImage(string base64String)
    {
      // Convert Base64 String to byte[]
      byte[] imageBytes = Convert.FromBase64String(base64String);
      MemoryStream stream = new MemoryStream(imageBytes, 0, 
      imageBytes.Length);

     // Convert byte[] to Image
     stream.Write(imageBytes, 0, imageBytes.Length);
     Image image = Image.FromStream(stream, true);
     return image;
   }