I am trying to transfer file from a java client to ac# server over UDP. However, when i try to open the transfered file(png picture) on the server side it doesn't succeed open it. Someone please can help me?
The client code:(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();
}
}
}
The server code:(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);
}
}
}
byte [] data = new byte[(int)myFile.length()];
That is your problem, you just initialize a new byte array with the length of myFile
. (not the actual data)
Here you can see how to convert your File to an actual Byte[]
( Files.toByteArray(File file)
)
First Before sending the picture, Decode it to a base64 string . A helper method here for encoding
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;
}
}
Encode it into byte array and send it
byte[] data = Encoding.ASCII.GetBytes(returnedStringFromEncoder);
Second : From the reciever side : convert the bytes array into string back
string data = Encoding.ASCII.GetString(recievedByteArray);
Finally Convert it into a picture back
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.