I’m writing a client server application, but I don’t receive the same bytes at the client side when they are sent from the server side.
At the server side I used .write(bytes[]) method. At the client side, I used .readFully(byte[]) method.
Do you have any idea ?
The sent code:
System.out.println("Server got connection from " + connectionFromClient.getPort());
in = connectionFromClient.getInputStream();
OutputStream out = connectionFromClient.getOutputStream();
DataOutputStream dataOut = new DataOutputStream(out);
LicenseList licenses = new LicenseList();
String ValidIDs = licenses.getAllIDs();
System.out.println(ValidIDs);
Encryption enc = new Encryption();
//byte[] dd = enc.encrypt(ValidIDs);
byte[] dd = enc.encrypt(ValidIDs);
String tobesent = new String(dd);
//byte[] rsult = enc.decrypt(dd);
//String tt = String(rsult);
System.out.println("The sent data**********************************************");
System.out.println(dd);
String temp = new String(dd);
System.out.println(temp);
System.out.println("*************************************************************");
//BufferedWriter bf = new BufferedWriter(OutputStreamWriter(out));
dataOut.write(ValidIDs.getBytes());
dataOut.flush();
System.out.println("********Testing**************");
System.out.println("Here are the ids:::");
System.out.println(licenses.getAllIDs());
System.out.println("**********************");
The client Side:
Socket connectionToServer = new Socket("127.0.0.1", 7050);
InputStream in = connectionToServer.getInputStream();
DataInputStream dis = new DataInputStream(in);
int available = dis.available();
byte[] data = new byte[available];
// dis.readFully(data);
dis.read(data);
System.out.println("The received Data*****************************************");
System.out.println(available);
System.out.println(data);
System.out.println("***********************************************************");
The contract of
in.available()does not guarantee anything. See the excerpt from the API below:Your code basically rely on / assume that all data sent, will be available immediately and reported accordingly by
in.available().To make sure you get all data, you could, on the sender side, start by sending an integer, telling how many bytes will be sent:
and then on the receiver side use that integer when creating the array:
Does the bytes you send come from a
String? In that case, you should be careful with the charset. The sender and receiver might have different default charsets.You could for instance use
str.getBytes("UTF-8")andnew String(bytes, "UTF-8")to be sure the receiver interprets the bytes the way the sender intended.