0

In example below I created one server which will only print whatever client is writing in a socket. But I am not getting output as client enter data. If client terminate then I can see all the data client inserted in outputstream. I am taking input from console at client and then write that data to server socket.

Server code:

   public class server {
public static void main(String[] args) throws Exception {
    System.out.println("waiting");
    ServerSocket s = new ServerSocket(9999);
    Socket stemp = s.accept();
    System.out.println("read comp");
    InputStream is = stemp.getInputStream();
    InputStreamReader ir = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(ir);

    while(true)
    {
        String str = br.readLine();
        if(str!=null)
        {
            System.out.println(str);
        }
        if(str.contains("exit"))
        {
            break;
        }
    }
    stemp.close();
    ir.close();
    is.close();
    br.close();
}
}

Client code:

public class client {
    public static void main(String[] args) throws Exception {
        String ip ="127.0.0.1";
        int port = 9999;
        Socket s1 = new Socket(ip, port);
        OutputStream os = s1.getOutputStream();
        OutputStreamWriter ow = new OutputStreamWriter(os);

        BufferedWriter pw = new BufferedWriter(ow);
        pw.write("I am ready");
        Scanner s = new Scanner(System.in);
        String str = s.nextLine();
        System.out.println(str);
        while(!str.contains("exit"))
        {
            pw.write(str);
            pw.flush();
            str = s.nextLine();
        }
        pw.close();
        os.close();
        ow.close();
        s1.close();
    }
}
1
  • 'Real time' has a specific meaning in computing, and this isn't it. Don't misuse standard terminology. Commented Mar 4, 2018 at 23:54

1 Answer 1

2

In server, br.readLine(); is used, waiting for end-of-line.

In client, you have to send the eol in pw.write( str + '\n' );.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.