Pinkesz
Pinkesz

Reputation: 37

Sending and receiving information between Sockets and ServerSockets

The following code is supposed to receive a time from a socket, add 6 months to the time and return it to the socket. Here is the code that initializes the sockets and servers:

    //open and connect the sockets
    ServerSocket ss = new ServerSocket(4444);
    System.out.println("1");
    Socket sock = new Socket(ss.getInetAddress(),4444);
    System.out.println("2");
    Socket srv = ss.accept();
    System.out.println("3");

Here is the code that shows the server receiving the time and adding 6 months to it (format of the time is YYYYMMDDHHMMSS).

    //send/receive and increment the current time by 6 months
    PrintWriter bw = new PrintWriter(sock.getOutputStream());
    System.out.println("4");
    bw.print(rtime);
    System.out.println("5");
    //add 6 months to the current time
    long ret = Long.valueOf(new BufferedReader(new InputStreamReader(srv.getInputStream())).readLine()) + 600000000;
    System.out.println("6");

The variable rtime, is a long that is already declared. The code is within a try{} followed by

    catch(Exception e) {
      System.out.println(e);
      System.exit(-1);
    }

I put the printing lines in the code to see where the error takes place, since for some reason, the program terminates without printing an error. All numbers get printed, until "6". In other words the error is met at the .readline() line. I don't know what I am doing wrong. Any help is much appreciated, thanks.

Upvotes: 0

Views: 133

Answers (1)

Pramod K P
Pramod K P

Reputation: 26

Please add

bw.flush();

after

bw.print(rtime);

This is required to flush the contents from client sockets output stream which would then be available at input of server socket.

Otherwise, in your example readline(); would not come out as it is a blocking call.

Upvotes: 1

Related Questions