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);
}
}
Your problem is that the
BufferedReaderis buffering bytes from the socket’s input stream, so the long 948 value isn’t in theDataInputStreambecause theBufferedReaderhas 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 yourServerclass, 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
DataInputStreamand along with the Server code, useDataInputStream.readUTF()on the Client while usingDataOutputStream.writeUTF()on the Server, getting rid of both theBufferedReaderand thePrintWriter.So on the Server:
}
and on the Client: