P
P
PlagueStarScream2017-08-11 10:14:21
Java
PlagueStarScream, 2017-08-11 10:14:21

Is the problem in java.net or something else?

I am writing a simple chat. There is a client and a server, each of them accepts and writes to the socket. But for some unknown reason, the server does not work as it should. By the condition above msg = null.

public void setNet(){
        try {
            ServerSocket serverSocket = new ServerSocket(5000);
                while (true){
                    System.out.println("while working");
                    Socket socket = serverSocket.accept();
                    InputStreamReader streamReader = new InputStreamReader(socket.getInputStream());
                    BufferedReader reader = new BufferedReader(streamReader);
                    msg = reader.readLine();
                    System.out.println(msg);
                    System.out.println("reader working");
                        if(msg != null){
                            writer = new PrintWriter(socket.getOutputStream());
                            writer.println(msg);
                            System.out.println("writer working");
                            writer.flush();
                            writer.close();
                         }
                         else {
                            System.out.println("msg = null");
                        }
                }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

If you comment out the line msg = reader.readLine(); then everything works fine.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Alexandrov, 2017-08-11
@jamakasi666

reader.readLine() waits for the end of the line to read it and you don't send it from the client.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question