简体   繁体   中英

Java Communication Server Client with Socket

i'm having trouble with my client/server program in java . I'm able to communicate from my client to my server but when i'm broadcasting from the server to the client it's not working. There is the part of my program that is not working : Server :

 while (true) {
            Socket socket = server.accept();


            out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));            
out.write("Welcome to the server !");
            out.flush();
}

Client ( running as a thread):

    while(true){
     try {
//s is the socket I get from the connection to the server          
 in = new BufferedReader (new InputStreamReader (s.getInputStream()));

                String msg = in.readLine();

                System.out.println(msg);

     } catch (IOException ex) {

     }     
        }

When I use my client programm I don't receive the message sent by the server . However when i use netcat on my terminal to establish the connection on the server, I got the message . I don't get it. Thanks

The client expects a complete line to be sent:

String msg = in.readLine();

It can only be sure the line is complete if it finds a line terminator character, or if the stream is closed. But the server doesn't send any EOL character, and doesn't close the stream either. So the client keeps waiting for the line to complete.

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