Hi I'm having some troubles with the readLong() method of DataInputStream. When I put a value via DataOutputStream.writeLong() it is the right value but when it is sent it is a lot bigger than it should be, I have the code all in a runnable statment so that the program doesn't freeze
this is the client
socket = new Socket(ipAddress, Port);
bos = new BufferedOutputStream(socket.getOutputStream());
dos = new DataOutputStream(bos);
File f = new File("C:/Users/lukeLaptop/Downloads/RemoveWAT22.zip");
long length = f.length();
dos.writeLong(length);
String name = f.getName();
dos.writeUTF(name);
FileInputStream fis = new FileInputStream(f);
bis = new BufferedInputStream(fis);
int theByte = 0;
while ((theByte = bis.read()) != -1) {
bos.write(theByte);
}
bis.close();
dos.close();
server side
ServerSocket server = new ServerSocket(8080);
while (true) {
socket = server.accept();
System.out.println("Got a client !");
bis = new BufferedInputStream(socket.getInputStream());
dis = new DataInputStream(bis);
int filesCount = dis.readInt();
long fileLength = dis.readLong();
//String fileName = dis.readUTF();
File f = new File("C:/test/here/test.zip");
FileOutputStream fos = new FileOutputStream(f);
BufferedOutputStream bos = new BufferedOutputStream(fos);
for (int j = 0; j < fileLength; j++) {
bos.write(bis.read());
}
bos.close();
dis.close();
EDIT
If any one can help me with the code it is much appreciated I'm new to sockets and I'm getting a bit confused on things, all I wanted is send the length of the file using the writeLong method of the dataoutputstream and send also the name with writeUTF but I don't know what is happening and how to fix it
The problem is the method writeUTF.
javadoc says:
Writes a string to the underlying output stream using modified UTF-8 encoding in a machine-independent manner.
First, two bytes are written to the output stream as if by the writeShort method giving the number of bytes to follow. This value is the number of bytes actually written out, not the length of the string. Following the length, each character of the string is output, in sequence, using the modified UTF-8 encoding for the character. If no exception is thrown, the counter written is incremented by the total number of bytes written to the output stream. This will be at least two plus the length of str, and at most two plus thrice the length of str.
But you use your own length encoding, that only takes the number of characters the string contains. It does not use the encoded length of your string.
You don't have to use your own length encoding if you use DataInputStream.readUTF() to read your string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With