dazbrad
dazbrad

Reputation: 182

client socket issues when reading

I am having a real problem trying to find a solution to my problem and hope you guys could help. I have seen many socket examples online but have been unable to modify them for my use. Tbh, im struggling to even get an understanding of sockets. What I have been able to modify so far is below.

My problem, I believe is that my client program is not reading the incoming message from the server, could someone use my example to demonstrate where I am going wrong. Something in my mind tells me that my client socket closes before having a chance to read any incoming message. perhaps getting the client to wait until a message is recieved? If waiting is what is needed, how is this achieved? Thanks in advance.

CLIENT:

try {
    Socket socket = new Socket("localhost", 55555);

    PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
    out.write(score);

    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    String rank = in.readLine();
    System.out.println(rank);

    in.close();            
    out.close();            
    socket.close();
}
catch(Exception e) {
    System.out.print("Whoops! It didn't work!\n");
}

SERVER:

try {
    System.out.println("Waitng for client to connect.....");
    ServerSocket server = new ServerSocket(55555);
    Socket socket = server.accept();
    System.out.print("Client has connected!\n");

    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    String score = (in.readLine());
    scor = Long.parseLong(score);
    leaderboard(); ///// A METHOD THAT USES LONG SCORE TO CALCULATE RANKING- RETURNS A STRING VALUE CALLED RANK

    PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
    System.out.print("Sending rank: " + rank);
    out.write(rank);

    out.close();
    socket.close();
    server.close();
}
catch(Exception e) {
    System.out.print("Whoops! It didn't work!\n")`enter code here`;
}

Upvotes: 2

Views: 145

Answers (1)

L457
L457

Reputation: 1032

Your code looks fine...

On your client program you're writing a line using:

out.write(score);

could you change this to:

out.println(score);

Also do the same on your server's program to take care of the reply:

out.println(rank);

Let me know how you go.. also if this helped, don't forget to upvote/mark this as a solution ;) cheers

(Btw,as to what caused the problem:: in.read'LINE'() waits for the end of a line or newline(\n) for the string value to be saved. if you use out.write() then you have to and a newline character(\n) manually for the string to be read completely. if you use out.printline, then \n is added automatically to every string sent.

The readline method in your program was waiting for a newline character, which is why your program was stuck in that spot)

Upvotes: 3

Related Questions