transfer file over udp - java

I am trying to transfer file from a java client to a c# 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;
}

Related

SMART Health Card QR java programming to read QR information [duplicate]

I was trying to decode the JWT payload in java but this payload is compressed/deflated
"zip": "DEF"
java.util.zip.DataFormatException: incorrect header check
private static byte[] decompress(byte[] value) throws DataFormatException {
ByteArrayOutputStream bos = new ByteArrayOutputStream(value.length);
Inflater decompressor = new Inflater();
try {
decompressor.setInput(value);
final byte[] buf = new byte[1024];
while (!decompressor.finished()) {
int count = decompressor.inflate(buf);
bos.write(buf, 0, count);
}
} finally {
decompressor.end();
}
return bos.toByteArray();
}
public static void main(String[] args) throws Exception {
String payload = "7VPbjtMwEP2X4TUXO9CumjdYkFghoZVaFiHUB9eZNka-RLYTUVb5d8ZuKxW09AuQ8jL2mTPnHGeeYZLQPkM8Dgjtd-hjHEJb18EIH3sUOvaVFL4Lr6SbVMdXUNzAnIoyFTdxypjRql8iKmdhW4D02KGNSuj1uPuBMiZJ-175J_QhYVp4U7GKE2k6fTfaTmPCeAxu9BI3WT6cL4qzHZBOa2JLDAXQAH8kj8Q8av3FawJc-ltGgEvxAvEjSaV-Allh8EQijNLEB-vN280HujmoCW3K8OvHh_Wnb7CdydlOkfX3IiYSvlqxkr2mD-a5eFEGvy3j4Tq3AkIUcQzZpxk0RkypT0JKZfHedZlBuk7ZQ1YcjiGiIXh6GHqXXt9Vzh_qFGkdVFfL6ScRyNwJDbuDeTsXMJy9Zzl79GiTtuvoEgj93nmDPk8SMjqfGjoVBi1SSvdP68deeCPkkdxTMk7K0WeyFM9GmdPQhpdsWTZLEqJd_DyaXeIE_s_Imv-RnSJb_BUZS5ltZ8oNlCAtfNks2HLBOKe_eLf_80CFcHaZN1ZFXopBVXIKl8V15nqR64nXec3n3w";
byte[] byt = Base64.getUrlDecoder().decode(new String(payload).getBytes("UTF-8"));
byte[] b = decompress(byt);
String s = new String(b, StandardCharsets.UTF_8);
}
Some other folks in other programming language was able to crack this out using this, wondering how will I accomplish this in java?
const decompressedCard = zlib.inflateRawSync(decodedPayload);
const card = JSON.parse(decompressedCard.toString());
Ususally compressed payload is used in encrypted JWTs (JWE), but SMART Health Cards also use it in signed tokens (JWS). In both cases, the DEFLATE format as defined in RFC1951 is used. For Zlib (as shown in the example on the bottom of the question) you have to use deflateRaw/inflateRaw (DEFLATE without any Zlib or gz headers).
In case of the java.util.zip.Inflater, initializing the inflater with
Inflater decompressor = new Inflater(true);
is setting the nowrap parameter to true to decompress in raw mode (without header) data,
which is equal to using inflateRaw in Node.js.
(see also https://docs.oracle.com/javase/7/docs/api/java/util/zip/Inflater.html)
With this setting, the code in the question works fine and the given example data can be inflated to a JSON.
The thing about nowrap is correct I think, but nonetheless, I wasn't able to get your code working until I fixed the corrupt input (mentioned above) and did this:
import java.util.Base64;
import java.util.zip.GZIPInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class Decomp2 {
public static byte[] gunzip(byte[] value) throws IOException {
byte[] result = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int numRead = -1;
try (GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(value))) {
while ((numRead = in.read(buf)) > -1) {
out.write(buf, 0, numRead);
}
result = out.toByteArray();
}
return result;
}
public static void main(String[] args) throws Exception {
// Data gzipped and b64url-encoded
String payload = "H4sIAKow-GAAA-1Ty27bMBC89zO2Vz1ItXZg3dokQIICRQC7CYrCB5paWwxIUSApoW6gf--StgG3SPwFAXRZcnZ2Zqh9gVFC_QJh3yPUv6ANofd1WXojXGhR6NAWUrjGf5R2VA1fQHYBcyjyWFzEKWOGTv0RQdkO1hlIhw12QQm9HDbPKEOUtG2Ve0TnI6aGzwUrOJHG069D12iMGIfeDk7iKsmH40V2tAPSak1skSEDGuD25JGYB61_OE2AU3_NCHAqXiF-IKnUT6BOGDyQCKM08cFy9WV1Szc7NWIXM3y6u19--wnriZxtFFm_ESGS8MWC5ewTfTBN2asy-GUZ9-e5ZeCDCINPPk2vMWBMfRRSqg6vbZMYpG1Ut0uK_d4HNASPD0Pv0uqrwrpdGSMtvWpKOf4mApk6oWJXMK2nDPqj9yRniw67qO08ughCt7XOoEuThAzWxYZG-V6LmNL14_KhFc4IuSf3lIyVcnCJLMazUuYwtOI5m-fVnIRoG74PZhM5gb8ZWfUe2SGy2X-RsZjZeqLcQAnSwufVjM1njHP6izfbfw-U90eXaWNV4LnoVSFHf1pca84XuRx5mdZ8-vAX5R6TWUMEAAA=";
byte[] byt = Base64.getUrlDecoder().decode(payload.getBytes("UTF-8"));
byte[] b = gunzip(byt);
String s = new String(b, StandardCharsets.UTF_8);
System.out.println(s);
}
}

Java inflate exception on raw data

I was trying to decode the JWT payload in java but this payload is compressed/deflated
"zip": "DEF"
java.util.zip.DataFormatException: incorrect header check
private static byte[] decompress(byte[] value) throws DataFormatException {
ByteArrayOutputStream bos = new ByteArrayOutputStream(value.length);
Inflater decompressor = new Inflater();
try {
decompressor.setInput(value);
final byte[] buf = new byte[1024];
while (!decompressor.finished()) {
int count = decompressor.inflate(buf);
bos.write(buf, 0, count);
}
} finally {
decompressor.end();
}
return bos.toByteArray();
}
public static void main(String[] args) throws Exception {
String payload = "7VPbjtMwEP2X4TUXO9CumjdYkFghoZVaFiHUB9eZNka-RLYTUVb5d8ZuKxW09AuQ8jL2mTPnHGeeYZLQPkM8Dgjtd-hjHEJb18EIH3sUOvaVFL4Lr6SbVMdXUNzAnIoyFTdxypjRql8iKmdhW4D02KGNSuj1uPuBMiZJ-175J_QhYVp4U7GKE2k6fTfaTmPCeAxu9BI3WT6cL4qzHZBOa2JLDAXQAH8kj8Q8av3FawJc-ltGgEvxAvEjSaV-Allh8EQijNLEB-vN280HujmoCW3K8OvHh_Wnb7CdydlOkfX3IiYSvlqxkr2mD-a5eFEGvy3j4Tq3AkIUcQzZpxk0RkypT0JKZfHedZlBuk7ZQ1YcjiGiIXh6GHqXXt9Vzh_qFGkdVFfL6ScRyNwJDbuDeTsXMJy9Zzl79GiTtuvoEgj93nmDPk8SMjqfGjoVBi1SSvdP68deeCPkkdxTMk7K0WeyFM9GmdPQhpdsWTZLEqJd_DyaXeIE_s_Imv-RnSJb_BUZS5ltZ8oNlCAtfNks2HLBOKe_eLf_80CFcHaZN1ZFXopBVXIKl8V15nqR64nXec3n3w";
byte[] byt = Base64.getUrlDecoder().decode(new String(payload).getBytes("UTF-8"));
byte[] b = decompress(byt);
String s = new String(b, StandardCharsets.UTF_8);
}
Some other folks in other programming language was able to crack this out using this, wondering how will I accomplish this in java?
const decompressedCard = zlib.inflateRawSync(decodedPayload);
const card = JSON.parse(decompressedCard.toString());
Ususally compressed payload is used in encrypted JWTs (JWE), but SMART Health Cards also use it in signed tokens (JWS). In both cases, the DEFLATE format as defined in RFC1951 is used. For Zlib (as shown in the example on the bottom of the question) you have to use deflateRaw/inflateRaw (DEFLATE without any Zlib or gz headers).
In case of the java.util.zip.Inflater, initializing the inflater with
Inflater decompressor = new Inflater(true);
is setting the nowrap parameter to true to decompress in raw mode (without header) data,
which is equal to using inflateRaw in Node.js.
(see also https://docs.oracle.com/javase/7/docs/api/java/util/zip/Inflater.html)
With this setting, the code in the question works fine and the given example data can be inflated to a JSON.
The thing about nowrap is correct I think, but nonetheless, I wasn't able to get your code working until I fixed the corrupt input (mentioned above) and did this:
import java.util.Base64;
import java.util.zip.GZIPInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class Decomp2 {
public static byte[] gunzip(byte[] value) throws IOException {
byte[] result = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int numRead = -1;
try (GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(value))) {
while ((numRead = in.read(buf)) > -1) {
out.write(buf, 0, numRead);
}
result = out.toByteArray();
}
return result;
}
public static void main(String[] args) throws Exception {
// Data gzipped and b64url-encoded
String payload = "H4sIAKow-GAAA-1Ty27bMBC89zO2Vz1ItXZg3dokQIICRQC7CYrCB5paWwxIUSApoW6gf--StgG3SPwFAXRZcnZ2Zqh9gVFC_QJh3yPUv6ANofd1WXojXGhR6NAWUrjGf5R2VA1fQHYBcyjyWFzEKWOGTv0RQdkO1hlIhw12QQm9HDbPKEOUtG2Ve0TnI6aGzwUrOJHG069D12iMGIfeDk7iKsmH40V2tAPSak1skSEDGuD25JGYB61_OE2AU3_NCHAqXiF-IKnUT6BOGDyQCKM08cFy9WV1Szc7NWIXM3y6u19--wnriZxtFFm_ESGS8MWC5ewTfTBN2asy-GUZ9-e5ZeCDCINPPk2vMWBMfRRSqg6vbZMYpG1Ut0uK_d4HNASPD0Pv0uqrwrpdGSMtvWpKOf4mApk6oWJXMK2nDPqj9yRniw67qO08ughCt7XOoEuThAzWxYZG-V6LmNL14_KhFc4IuSf3lIyVcnCJLMazUuYwtOI5m-fVnIRoG74PZhM5gb8ZWfUe2SGy2X-RsZjZeqLcQAnSwufVjM1njHP6izfbfw-U90eXaWNV4LnoVSFHf1pca84XuRx5mdZ8-vAX5R6TWUMEAAA=";
byte[] byt = Base64.getUrlDecoder().decode(payload.getBytes("UTF-8"));
byte[] b = gunzip(byt);
String s = new String(b, StandardCharsets.UTF_8);
System.out.println(s);
}
}

Java string comparison with equals() not working as expected with UDP

I am trying to send a message over UDP and comparing it with a string literal, but it does not seem to work.
Here is the UDP server code
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Controller {
public static void main(String args[]) {
//create UDP server
try {
DatagramSocket socket = new DatagramSocket(5002);
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
//wait for done message
socket.receive(packet);
String msg = new String (packet.getData());
if(msg.equals("Done"))
{
System.out.println("Done received");
}
else {
System.out.println("Done not received");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
And here is the UDP client code
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Slave {
public static void main(String args[]) {
//create UDP client
try {
DatagramSocket socket = new DatagramSocket();
byte[] buffer;
//send Done message
buffer = "Done".getBytes();
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, InetAddress.getLocalHost(), 5002);
socket.send(packet);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The output I get is "done not received", even though done message is sent. What is wrong with the code?
The problem is, that you are declaring a buffer with 1024 bytes, which you are the converting to a string. That string does not equal "Done", it is simply "too long". You have to obtain the actual length of your sent data. You could do something like this in your Controller:
public class Controller {
public static void main(String args[]) {
//create UDP server
try {
DatagramSocket socket = new DatagramSocket(5002);
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
//wait for done message
socket.receive(packet);
//Get actual data length and copy it
byte[] data = new byte[packet.getLength()];
System.arraycopy(packet.getData(), packet.getOffset(), data, 0, packet.getLength());
//Create string from actual data
String msg = new String (data);
if(msg.equals("Done"))
{
System.out.println("Done received");
}
else {
System.out.println("Done not received");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
String msg = new String(packet.getData(), packet.getOffset(), packet.getLength());
DatagramPacket contains other information such as the port and host. Calling new String() on the data will extract more information than just the data message. Using packet.getData() and setting the offset will make sure that you extract just the data in the packet and leave out the port and host.
See the JavaDocs for DatagramPacket for more information.
When I debug your code, I can see that the message is "Done" with a lot of following '\u0000' which seems to be a unicode represantation of 0
So you either remove the zeros or you change your if statement to
msg.startsWith("Done")

How to send Vector over UDP conection in JAVA

I am trying to send vector object from UDP server to UDP client in Java.
Sending and Receiving string as an object after serializing has been achieved , but I am unable to send or receive vectors. Below is server ide code.
public class UDPReceive {
public UDPReceive() throws IOException {
try {
int port = Integer.parseInt("1233");
int allReceived=0;
String[] custData=new String[3];
DatagramSocket dsocket = new DatagramSocket(port);
byte[] buffer = new byte[2048];
for(;;) {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
dsocket.receive(packet);
String msg = new String(buffer, 0, packet.getLength());
String msg2 = new String(packet.getData());
custData[allReceived]=msg;
allReceived++;
if(allReceived == 3){
System.out.println("All Data Received");
for(int i=0;i<3;i++){
System.out.println(custData[i]);
}
Vector rawData=getTransactions(custData[0],custData[1],custData[2]);
System.out.println("Vectot size "+ rawData.size());
byte[] sendData = new byte[1024];
sendData=(object[])rawData.toArray();
allReceived=0;
}/*if ends here */
}
}
catch (Exception e) {
System.err.println(e);
}
}
Here I want to send back "rawData" variable to client and receive it, and covert it to vector in client side. I tried using byte[] as well, but it didn't work
I suggest you serialize the Vector as an ObjectOutputStream and use ObjectInputStream to get the original Vector.
public static byte[] objectToBytes(Object o) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(o);
oos.close();
return baos.toByteArray();
}
to reverse
public static <T> T bytesToObject(byte[] bytes) throws IOException, ClassNotFoundException {
return (T) new ObjectInputStream(new ByteArrayInputStream(bytes)).readObject();
}

Decode UDP message (from Erlang to Java)

I just tried to send a message by UDP from an Erlang server to a Java client. Now I am wondering how I should do to interpret this message to something useful.
Here is what I wrote in Erlang:
{ok, Socket} = gen_udp:open(8789, [binary, {active, true}]).
gen_udp:send(Socket, {127,0,0,1},11001, "yeah!").
And here is my Java code:
public class Server {
private DatagramSocket socket;
private byte[] buffer;
public Server() {
try {
socket = new DatagramSocket(11001);
} catch (SocketException e) {
e.printStackTrace();
}
buffer = new byte[65508];
}
public void receivePackage() {
try {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
byte[] buffer = packet.getData();
System.out.println(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
}
How do I handle the byte buffer and translate it to something that I can output in the Java console?
on the Erlang side try to send
binary instead of string :
gen_udp:send(Socket, {127,0,0,1},11001, <<"yeah!">>).
On java side:
byte[] b1 = new byte[] {#your byte array};
String s2 = new String(b1);
This will parse binary data to string.

Categories

Resources