简体   繁体   中英

Client's BufferedReader not recieving line from Server, using sockets (Java)

I'm trying to make a chat application between a server and clients which are seperate classes. I'm not copying the whole code, but this is the part I'm not sure is set up correctly:

Server:

    ServerSocket s = null;
    Socket c = null;
    s = new ServerSocket(5002);

    c = s.accept();


    BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()))
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(c.getOutputStream()));

    out.flush();
    String line;
    line = in.readLine();
    out.write("#W|Welcome");
    line = in.readLine();
    out.write("#W|Welcome");
    line = in.readLine();
    out.write("#W|Welcome");

Client :

    Socket socket = new Socket("localhost", 5002);

    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream  ()));
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

    String line;
    out.flush();
    out.write("#J|test");
    line = in.readLine();
    out.write("#J|test");
    line = in.readLine();

After the client does out.println() , the server's in.readLine() gets the line. But when it's the other way around, the client keeps waiting at in.readLine() . (I used the debugger and watched the server execute out.println() and go past it, while the client is still stuck at in.readLine() .

Are my data streams set up correctly or is there probably an error in my code somewhere else? I'm not sure how to check in the debugger if the streams are connected correctly.

[Quoting my comment above:]

There is nothing here that [reads or] writes lines.

That remains true. All you have is:

out.write("#W|Welcome");

etc.

don't forget to call newLine() as necessary

You forgot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM