7

I have a problem using sockets in Java: the server doesn't respond and no exception is thrown.

Server Code:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

class Server {
    public static void main(String args[]) {
        final int time = 75;
        //boolean CHAT_SESSION_ALIVE = false; 
        int port = 9999;

        try {
            System.out.println("Starting chat server using the port : " + port);
            ServerSocket srvr = new ServerSocket(port);
            Socket skt = srvr.accept();
            System.out.println("Server has connected with client         " + skt.getInetAddress());
            //CHAT_SESSION_ALIVE = true;

            PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));

            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            if (in.ready()) {
                                String msg = in.readLine();
                                System.out.println("receive message: '" + msg + "'");
                                Thread.sleep(time);
                            }
                        } catch (Exception e) {
                            System.out.println(e);
                        }
                    }
                }
            }).start();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            Thread.sleep(time);
                            String msg = new Scanner(System.in).nextLine();
                            System.out.println("Sending message: '" + msg + "'");
                            out.print(msg);
                        } catch (Exception e) {
                            System.out.println(e);
                        }
                    }
                }
            }).start();

            //in.close();
            //out.close();
            //skt.close();
            //srvr.close();
        } catch (Exception e) {
            System.out.print(e);
        }
    }
}

Client Code:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

class Client {
    public static void main(String args[]) {
        final int time = 75;
        //boolean CHAT_SESSION_ALIVE = false;
        int port = 9999;
        String hostIP = "127.0.0.1";

        try {
            Socket skt = new Socket(hostIP, port);
            System.out.println("Client has connected with server " + hostIP + ":" + port);
            //CHAT_SESSION_ALIVE = true;

            PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));

            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            if (in.ready()) {
                                String msg = in.readLine();
                                System.out.println("receive message: '" + msg + "'");
                                Thread.sleep(time);
                            }
                        } catch (Exception e) {
                            System.out.println(e);
                        }
                    }
                }
            }).start();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            String msg = new Scanner(System.in).nextLine();
                            System.out.println("Sending message: '" + msg + "'");
                            out.print(msg);
                            Thread.sleep(time);
                        } catch (Exception e) {
                            System.out.println(e);
                        }
                    }
                }
            }).start();

            //in.close();
            //out.close();
            //skt.close();
        } catch (Exception e) {
            System.out.print(e);
        }
    }
}

The server output:

Starting chat server using the port : 9999
Server has connected with client /127.0.0.1

The client output:

Client has connected with server 127.0.0.1:9999
simple message
Sending message: 'simple message'

Please explain why the server isn't working correctly.

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
IORI YAGAMI
  • 71
  • 1
  • 2

2 Answers2

3

Scanner.nextLine returns the line without the new line delim. The server is using BufferedReader.readLine, which expects a new line (or may block if it does not receive one). Solution: append the delimiter when sending messages. If using print, you must explicitly flush:

out.print(msg + "\n"); 
out.flush();//explicitly flush the stream

or use the println method to have it add the new line for you (and makes use of autoflush true flag passed to the PrintWriter constructor):

out.println(msg);//auto flushing 
copeg
  • 8,290
  • 19
  • 28
  • Alternately, you could just call `out.println(msg);` instead of adding the line delimiter yourself. – 1337joe May 21 '15 at 13:36
  • 1
    @1337joe: Also, you could call `printf()`, which will let you pass in the system-specific delimiter. -> `out.printf("%s%n", msg);` [(More info on `%n`)](http://stackoverflow.com/questions/1883345/whats-up-with-javas-n-in-printf). – Mr. Polywhirl May 21 '15 at 13:39
  • @copeg: If you still want to use `print()`, you could alternatively use: `out.print(msg + System.getProperty("line.separator"));` – Mr. Polywhirl May 21 '15 at 13:42
  • @Mr. Polywhirl, yes, thanks. Note that although autoflush is enabled, if calling `print` one must explicitly flush – copeg May 21 '15 at 13:46
  • thanks a lot, there is no any changes in the output I think that another problem existing in the code – IORI YAGAMI May 21 '15 at 15:57
  • @IORI YAGAMI, please edit your question with the updated code. – copeg May 21 '15 at 15:58
0

In both codes, put an out.flush() just right after the instanciation of PrintWriter out

Am_I_Helpful
  • 18,735
  • 7
  • 49
  • 73