2

Why does this program not work properly? Client reads SOME_MESSAGE and after that nothing happens. It seems that println method from server in some way have influence on transferring long type numbers.

SERVER

import java.net.*;
import java.io.*;

public class Server {

  public static void main(String[] args) throws Exception {
    ServerSocket socket = new ServerSocket(9999);
    while (true) {
      Socket sock = socket.accept();
      PrintWriter out = new PrintWriter(new BufferedWriter(
          new OutputStreamWriter(sock.getOutputStream())), true);
      DataOutputStream outByte = new DataOutputStream(sock.getOutputStream());
      out.println("SOME_MESSAGE");
      outByte.writeLong(948L);
    }
  }
}

CLIENT

import java.net.*;
import java.io.*;

public class Client {

  public static void main(String[] args) throws Exception {
    Socket sock = new Socket("127.0.0.1", 9999);
    DataInputStream inByte = new DataInputStream(sock.getInputStream());
    BufferedReader in = new BufferedReader(new InputStreamReader(
        sock.getInputStream()));

    System.out.println(in.readLine());
    long number = inByte.readLong();
    System.out.println(number);
  }
}
4
  • Works for me when I tested it (Java 7). Aug 20, 2012 at 8:26
  • Does it work if you place the println and writeLong inside synchronized(this) { ... } blocks?
    – martijno
    Aug 20, 2012 at 8:32
  • @martijno What would be the rationale behind that? Aug 20, 2012 at 8:33
  • I was thinking part of the problem might be that you're writing data to the underlying OutputStream via two different wrappers (out and outByte), both of which have internal buffers. Actually, synchronization doesn't help here of course, never mind. Perhaps flushing in between the calls?
    – martijno
    Aug 20, 2012 at 8:42

2 Answers 2

3

Your problem is that the BufferedReader is buffering bytes from the socket's input stream, so the long 948 value isn't in the DataInputStream because the BufferedReader has it read and is buffering it. In general you don't want to be using 2 different wrappers around the same underlying stream, especially if one is buffered. Same with your Server class, but that seems to at least be working.

Your Client needs to use only one wrapper for the socket's input stream. You should just stick with the DataInputStream and along with the Server code, use DataInputStream.readUTF() on the Client while using DataOutputStream.writeUTF() on the Server, getting rid of both the BufferedReader and the PrintWriter.

So on the Server:

while(true) {
    Socket sock = socket.accept();
    DataOutputStream outByte = new DataOutputStream(sock.getOutputStream());
    outByte.writeUTF("SOME_MESSAGE");
    outByte.writeLong(948L);
    outByte.flush();

}

and on the Client:

public static void main(String[]args)throws Exception
{
    Socket sock = new Socket("127.0.0.1",9999);
    DataInputStream inByte = new DataInputStream(sock.getInputStream());

    System.out.println(inByte.readUTF());
    long number  = inByte.readLong();
    System.out.println(number);
}
14
  • I agree to the solution but I am not convinced about why this is happening? PrintWriter if autoflush true will flush the data written that is why "SOME_MESSAGE" is received at the client side. Now even if both streams flushed after writing long then also 'long' is never received at client side it is like disappeared? Aug 20, 2012 at 9:36
  • Thanks for advice. I have accustomed to use PrintWriter and Scanner to communicate, but the problem was i needed to transfer file so i had to use InputStream and OutputStream beside Scanner and PrintWriter. How can i convert from UTF-8 to default character set when i read with readUTF() and for how much bytes will writeUTF() increase size of transfered characters throw network? Aug 20, 2012 at 9:36
  • @AmitDeshpande The problem isn't on the Server's end and the flushing, it's the Client reading. The BufferedReader reads the Long from sock.getInputStream() and it's buffered, so when you call readLong(), the underlying sock.getInputStream() has nothing to be read.
    – Jon Lin
    Aug 20, 2012 at 9:39
  • @user1610362 You won't need to convert anything because you have String objects already, the encoding is purely for transferring through the DataInput/Output streams. The UTF methods use a modified UTF-8, so there isn't any extra size being transferred, and in the case of actual UTF-8 data, it is less bytes to use read/writeUTF().
    – Jon Lin
    Aug 20, 2012 at 9:44
  • Can i buffer DataOutputStream and DataInputStream? Aug 20, 2012 at 9:53
0

It is interesting that java does not allow to do that having said that there is always a better solution. You can use serialization to do your job.

create a interface PayLoad like below

import java.io.Serializable;


public interface PayLoad extends Serializable
{
String getMessage();
//Java does not allow to define byte array of long
int getLength();

byte[] getbytes();

}

Then create an Implementation class like below

public class FilePayLoad implements PayLoad
{

private final String message;
private final int length;
private final byte[] bytes;

public FilePayLoad(String message, int length, byte[] bytes)
{
    this.message = message;
    this.length = length;
    this.bytes = bytes;

}

@Override
public String getMessage()
{
    return this.message;
}

@Override
public int getLength()
{
    return this.length;
}

@Override
public byte[] getbytes()
{
    return this.bytes;
}

}

Now change your server and client like below

Server

public class Server
{

public static void main(String[] args) throws Exception
{
    ServerSocket socket = new ServerSocket(9999);
    while (true)
    {
        Socket sock = socket.accept();
        ObjectOutputStream out = new ObjectOutputStream(sock.getOutputStream());
        byte[] bytes = "SOME_MESSAGE".getBytes();
        out.writeObject(new FilePayLoad("SOME_MESSAGE", bytes.length, bytes));
        out.flush();
    }
}
}

Client

public class Client
{
public static void main(String[] args) throws Exception
{
    Socket sock = new Socket("127.0.0.1", 9999);
    ObjectInputStream inByte = new ObjectInputStream(sock.getInputStream());
    PayLoad payLoad = (PayLoad) inByte.readObject();
    System.out.println(payLoad.getMessage());
    System.out.println(payLoad.getLength());
    System.out.println(new String(payLoad.getbytes()));
}

}
1
  • I know that but i needed to use DataInputStream to read bytes from stream with read(byte[],off,len) because later in code i transferred byte files so i also used that for reading that long number which in my case represent size of file. Aug 20, 2012 at 10:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.