HỎI [HELP] Em đang gặp vấn đề khi chạy code đồng bộ thời gian trên client - server

vananh2222

New Member
25/8/20
5
0
1
Da Nang
Chào mọi người, hiện tại em đang làm bài tập đồng bộ thời gian trên hệ thống client server. Em chạy code Server trên máy chính, và chạy client trên máy ảo VituralBox
Em đã chạy Server trước, sau đó chạy Client thì luôn bị báo lỗi java.net.connectexception connection refused connect
Em đã cho tường lửa thông qua Java rồi ạ

Mong mọi người giúp đỡ ạ. Em cảm ơn ạ
 
Sửa lần cuối:

vananh2222

New Member
25/8/20
5
0
1
Da Nang
Chạy 2 file trên cùng một máy thì có kết nối, nhưng trên 2 máy thì luôn báo lỗi ạ
 

Joe

Thành viên VIP
21/1/13
2,969
1,310
113
Chạy 2 file trên cùng một máy thì có kết nối, nhưng trên 2 máy thì luôn báo lỗi ạ
When Client and Server run on the same machine the connection is always OK because Client and server share the same internal IP address (Here: 192.168.0.150 ) and the port is known locally (local or LAN)

If you run the Client in a VirtualBox the Client cannot connect to the Server because the VirtualBox works as if it was UNRELATED to the host (Windows or Linux) as an external machine. Therefore the client DOES NOT KNOW the internal IP address with the given port used by the Server. To make the connection possible you have to make "PORT forwarding" of the port on the modem. How? Click HERE to learn more for details.
 
Sửa lần cuối:
  • Like
Reactions: vananh2222

vananh2222

New Member
25/8/20
5
0
1
Da Nang
When Client and Server run on the same machine the connection is always OK because Client and server share the same internal IP address (Here: 192.168.0.150) and the port is known locally (local or LAN)

If you run the Client in a VirtualBox the Client cannot connect to the Server because the VirtualBox works as if it was UNRELATED to the host (Windows or Linux) as an external machine. Therefore the client DOES NOT KNOW the internal IP address with the given port used by the Server. To make the connection possible you have to make "PORT forwarding" of the port on the modem. How? Click HERE to learn more for details.
Thank you so much Joe, I followed the instructions but the results are the same. Maybe tomorrow I will try to connect on my laptop and pc.
Capture2.PNG
Capture1.PNG
Capture.PNG
 
Last edited by a moderator:

vananh2222

New Member
25/8/20
5
0
1
Da Nang
When Client and Server run on the same machine the connection is always OK because Client and server share the same internal IP address (Here: 192.168.0.150) and the port is known locally (local or LAN)

If you run the Client in a VirtualBox the Client cannot connect to the Server because the VirtualBox works as if it was UNRELATED to the host (Windows or Linux) as an external machine. Therefore the client DOES NOT KNOW the internal IP address with the given port used by the Server. To make the connection possible you have to make "PORT forwarding" of the port on the modem. How? Click HERE to learn more for details.
Hi sir, I connected to client server successfully but still can't sync the time. Can you help me identify the problem in the code? I can't spot the error anywhere
 
Last edited by a moderator:

Joe

Thành viên VIP
21/1/13
2,969
1,310
113
can't sync the time
Your Client and Server codes are too redundant and unsynchronized Read-Write operations between Client and Server. I have modified the last part of Client and Server to show you how to synchronize the RW Operations between Client and Server. With the modifications you could extend the correction to the rest of other Client parts.

Client
Java:
      boolean OK = false;
      ...
      }else{
        clientSocket = new Socket("localhost", 14500);
        OutToServer = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
        InFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        OutToServer.write("Communicating with Server" + '\n');
        OutToServer.flush();
        String line = InFromServer.readLine().trim();
        System.out.println(line);
        //
        byte[] bb = new byte[1024];
        while(true){
          System.out.println("Press Enter to terminate.");
          int n = System.in.read(bb);
          line = (new String(bb, 0, n)).trim();
          if (line.length() == 0) {
            OutToServer.write("Quit\n");
            OutToServer.flush();
            break;
          }
          OutToServer.write(line+"\n");
          OutToServer.flush();
          line = InFromServer.readLine().trim();
          System.out.println(line);
        }
        OutToServer.close();
        InFromServer.close();
        clientSocket.close();
        OK = true;
      }
    }
    catch(Exception e){
      if (!OK) e.printStackTrace();
    }
and Server
Java:
    ....
    public void run()
    {
      try {
       inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));

       //using output stream responding data
        outToClient = new BufferedWriter(new OutputStreamWriter(connectionSocket.getOutputStream()));
        while (true) {
            //opening the input stream to read data from client connection
            String line = inFromClient.readLine().trim();
            if("Switch".equals(line))
            {
                 //format date to send
                     DateFormat dateFormat = new SimpleDateFormat("MMMMMMMMMM dd, yyyy");
                     DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
                     Date date = new Date();
                     DateFormat outDate = new SimpleDateFormat("dd MM yyyy");
                     //send the day and time
                     outToClient.write(outDate.format(date) + " ");
                     outToClient.write(timeFormat.format(date) + '\n');
                     outToClient.flush();
                     //print the time and day the timestamp was sent
                     System.out.print("Sent timestamp on ");
                     System.out.print(dateFormat.format(date));
                     System.out.print(" at ");
                     System.out.print(timeFormat.format(date));
                     System.out.println(" to " + connectionSocket.getInetAddress());
            } else {
              System.out.println("From Client:"+line);
              outToClient.write("from Server:" +line+ "\n");
              outToClient.flush();
              if ("Quit".equals(line)) try {
                inFromClient.close();
                outToClient.close();
                connectionSocket.close();
                return; //exit
              } catch (Exception ex) { }
            }
        }
            //closing the in & out streams
            //out.close();
            //inFromClient.close();

        }
        catch(Exception e)
        {
            //System.out.println("Unable to connect with the Client!" + e);
        }
    }
 
  • Like
Reactions: vananh2222

vananh2222

New Member
25/8/20
5
0
1
Da Nang
Your Client and Server codes are too redundant and unsynchronized Read-Write operations between Client and Server. I have modified the last part of Client and Server to show you how to synchronize the RW Operations between Client and Server. With the modifications you could extend the correction to the rest of other Client parts.

Client
Java:
      boolean OK = false;
      ...
      }else{
        clientSocket = new Socket("localhost", 14500);
        OutToServer = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
        InFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        OutToServer.write("Communicating with Server" + '\n');
        OutToServer.flush();
        String line = InFromServer.readLine().trim();
        System.out.println(line);
        //
        byte[] bb = new byte[1024];
        while(true){
          System.out.println("Press Enter to terminate.");
          int n = System.in.read(bb);
          line = (new String(bb, 0, n)).trim();
          if (line.length() == 0) {
            OutToServer.write("Quit\n");
            OutToServer.flush();
            break;
          }
          OutToServer.write(line+"\n");
          OutToServer.flush();
          line = InFromServer.readLine().trim();
          System.out.println(line);
        }
        OutToServer.close();
        InFromServer.close();
        clientSocket.close();
        OK = true;
      }
    }
    catch(Exception e){
      if (!OK) e.printStackTrace();
    }
and Server
Java:
    ....
    public void run()
    {
      try {
       inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));

       //using output stream responding data
        outToClient = new BufferedWriter(new OutputStreamWriter(connectionSocket.getOutputStream()));
        while (true) {
            //opening the input stream to read data from client connection
            String line = inFromClient.readLine().trim();
            if("Switch".equals(line))
            {
                 //format date to send
                     DateFormat dateFormat = new SimpleDateFormat("MMMMMMMMMM dd, yyyy");
                     DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
                     Date date = new Date();
                     DateFormat outDate = new SimpleDateFormat("dd MM yyyy");
                     //send the day and time
                     outToClient.write(outDate.format(date) + " ");
                     outToClient.write(timeFormat.format(date) + '\n');
                     outToClient.flush();
                     //print the time and day the timestamp was sent
                     System.out.print("Sent timestamp on ");
                     System.out.print(dateFormat.format(date));
                     System.out.print(" at ");
                     System.out.print(timeFormat.format(date));
                     System.out.println(" to " + connectionSocket.getInetAddress());
            } else {
              System.out.println("From Client:"+line);
              outToClient.write("from Server:" +line+ "\n");
              outToClient.flush();
              if ("Quit".equals(line)) try {
                inFromClient.close();
                outToClient.close();
                connectionSocket.close();
                return; //exit
              } catch (Exception ex) { }
            }
        }
            //closing the in & out streams
            //out.close();
            //inFromClient.close();

        }
        catch(Exception e)
        {
            //System.out.println("Unable to connect with the Client!" + e);
        }
    }
Thank you so much Joe! You're so nice! I understood something. Currently I have shortened and improved my code. I was able to synchronize clocks on client / server. But I still can't sync the date. I can't figure out the problem, there is always a problem with the date format on the client / server. I hope you can help me answer it. thanks so much, Joe!!!!
 
Sửa lần cuối:

Joe

Thành viên VIP
21/1/13
2,969
1,310
113
Here is my code: (sync date and clock has error)
The basic rules (or conventions) of JAVA are:
  1. the file name must share the same name of the public class. Exmaple: serverdemoo.java for public class serverdemoo or clientdemoooo.java for public class clientdemoooo (see the error message)
  2. the sequence of closing action is: FIRST Input or output THEN socket. Not Socket then In/Output
case 1: error message
Code:
Main.java:10: error: class serverdemoo is public, should be declared in a file named serverdemoo.java
public class serverdemoo{
       ^
1 error
case 2: Exception if Socket is closed before closing In/Output
Java:
                dos.close();  // Output stream
                s1.close();   // <-- Socket after dos
 
Sửa lần cuối: