客户端无法从服务器获取日期(Java)。

huangapple go评论81阅读模式
英文:

Client cannot get date from Server in Java

问题

我正在编写代码,从服务器获取日期传输到客户端。但是当我运行时,结果为 `null`。<br>
我无法理解为什么会这样,而且我在从服务器到客户端的日期格式方面也遇到了问题。

我可以同步时钟,但无法同步日期。<br>
**我需要帮助:** 我想要从服务器同步客户端的日期和时钟。

**服务器:**

```java
public class ServerDemo{
    public static void main(String []args) throws IOException{
        ServerSocket s = new ServerSocket(50555);
        int server_timeout = 10000;
        s.setSoTimeout(server_timeout);
        displayBanner();
        System.out.println("|\n|-Server is running...");

        try{
            while(true){
                Socket  s1 = s.accept();
                System.out.println("|\n|-Connection Received : " + s1);
                BufferedWriter dos = new BufferedWriter(new OutputStreamWriter(s1.getOutputStream()));
                
                SimpleDateFormat outDate = new SimpleDateFormat("dd/MM/yyyy");

                //DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
                
                Date dt = new Date();
                System.out.println("    |\n    |-Sent to client :  " + dt);
                dos.write(outDate.format(dt) + " ");
                //dos.writeChars(timeFormat.format(dt) + '\n');

                System.out.println("    |\n    |-Connection Terminated : " + s1);
                s1.close();
                dos.close();
                
            }
        } catch(SocketTimeoutException e){
            System.out.println("|\nTerminating server due to timeout...");
            System.out.println("Server is terminated!");
            s.close();
        }
    }
    
    System.out.println("[+]--Clock Synchronization Server v1.0.1--- initializing...");
}

客户端:

public class ClientDemo{
    public static void main(String []args) throws Exception{
        
        Socket s = new Socket("192.168.1.190", 50555);

        BufferedReader InFromServer = new BufferedReader(new InputStreamReader(s.getInputStream()));
        BufferedWriter OutToServer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        
        String date = InFromServer.readLine();
        System.out.println(date);
        
        /*
        DateFormat Format = new SimpleDateFormat("dd/MM/yyyy");
        //parse the data from the server
        Date serverDate = Format.parse(date);
        //format the server for the Runtime commands
        DateFormat newFormatDate = new SimpleDateFormat("dd-MM-yy");
        String sysdate = "" + newFormatDate.format(serverDate);
        System.out.println(sysdate);
        */
        
        InFromServer.close();
        s.close();
    }
}

<details>
<summary>英文:</summary>

I&#39;m writing code to get date from server to client. But when I run, result is `null`.&lt;br&gt;
I can&#39;t understand why and I also have trouble in format day from Server to Client.

I can sync clock, but I cannot sync date.&lt;br&gt;
**I need a help:** I want to sync date and clock on client from server

**Server:**

    public class ServerDemo{
	public static void main(String []args) throws IOException{
		ServerSocket s = new ServerSocket(50555);
		int server_timeout = 10000;
		s.setSoTimeout(server_timeout);
		displayBanner();
		System.out.println(&quot;|\n|-Server is running...&quot;);

		try{
			while(true){
				Socket  s1 = s.accept();
				System.out.println(&quot;|\n|-Connection Received : &quot; + s1);
				BufferedWriter dos = new BufferedWriter(new OutputStreamWriter(s1.getOutputStream()));
				
				SimpleDateFormat outDate = new SimpleDateFormat(&quot;dd/MM/yyyy&quot;);

				//DateFormat timeFormat = new SimpleDateFormat(&quot;HH:mm:ss&quot;);
				
				Date dt = new Date();
				System.out.println(&quot;    |\n    |-Sent to client :  &quot; + dt);
				dos.write(outDate.format(dt) + &quot; &quot;);
				//dos.writeChars(timeFormat.format(dt) + &#39;\n&#39;);

				System.out.println(&quot;    |\n    |-Connection Terminated : &quot; + s1);
				s1.close();
				dos.close();
				
			}
		} catch(SocketTimeoutException e){
			System.out.println(&quot;|\nTerminating server due to timeout...&quot;);
			System.out.println(&quot;Server is terminated!&quot;);
			s.close();
		}
		
	}

	
	    System.out.println(&quot;[+]--Clock Synchronization Server v1.0.1--- initializing...&quot;);
	}

**Client:**

    public class ClientDemo{
	public static void main(String []args) throws Exception{
		
		Socket s = new Socket(&quot;192.168.1.190&quot;, 50555);

		BufferedReader InFromServer = new BufferedReader(new InputStreamReader(s.getInputStream()));
		BufferedWriter OutToServer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
		
		String date = InFromServer.readLine();
		System.out.println(date);
		
		/*
		DateFormat Format = new SimpleDateFormat(&quot;dd/MM/yyyy&quot;);
		//parse the data from the server
		Date serverDate = Format.parse(date);
		//format the server for the Runtime commands
		DateFormat newFormatDate = new SimpleDateFormat(&quot;dd-MM-yy&quot;);
		String sysdate = &quot;&quot; + newFormatDate.format(serverDate);
		System.out.println(sysdate);
		*/
		
		InFromServer.close();
		s.close();
		
	}

</details>


# 答案1
**得分**: 0

`dos.flush();` 是关键。以下是已稍作修改的工作类:

服务器端:

```java
public class ServerDemo {

    public static void main(String[] args) throws IOException {
        ServerSocket s = new ServerSocket(50555);
        int server_timeout = 30000;
        s.setSoTimeout(server_timeout);
        System.out.println("|\n|-服务器正在运行...");

        try {
            while (true) {
                Socket s1 = s.accept();
                System.out.println("|\n|-已接收连接 : " + s1);
                BufferedWriter dos = new BufferedWriter(new OutputStreamWriter(s1.getOutputStream()));

                SimpleDateFormat outDate = new SimpleDateFormat("dd/MM/yyyy");

                Date dt = new Date();
                System.out.println("    |\n    |-发送给客户端 :  " + dt);
                dos.write(outDate.format(dt) + " ");
                dos.flush(); // <- 这是关键
                dos.close();
                s1.close();
            }
        } catch (SocketTimeoutException e) {
            System.out.println("|\n因超时终止服务器...");
            System.out.println("服务器已终止!");
            s.close();
        }
    }
}

客户端:

package serverClient;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class ClientDemo {

    public static void main(String[] args) throws Exception {
        Socket s = new Socket("127.0.0.1", 50555);
        BufferedReader InFromServer = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String date = InFromServer.readLine();
        System.out.println(date);
        InFromServer.close();
        s.close();
    }
}
英文:

dos.flush(); is the key. Here are the working classes (slightly changed):

Server side:

public class ServerDemo {

    public static void main(String[] args) throws IOException {
        ServerSocket s = new ServerSocket(50555);
        int server_timeout = 30000;
        s.setSoTimeout(server_timeout);
        System.out.println(&quot;|\n|-Server is running...&quot;);

        try {
            while (true) {
                Socket s1 = s.accept();
                System.out.println(&quot;|\n|-Connection Received : &quot; + s1);
                BufferedWriter dos = new BufferedWriter(new OutputStreamWriter(s1.getOutputStream()));

                SimpleDateFormat outDate = new SimpleDateFormat(&quot;dd/MM/yyyy&quot;);

                Date dt = new Date();
                System.out.println(&quot;    |\n    |-Sent to client :  &quot; + dt);
                dos.write(outDate.format(dt) + &quot; &quot;);
                dos.flush(); //&lt;- this is essential
                dos.close();
                s1.close();
            }
        } catch (SocketTimeoutException e) {
            System.out.println(&quot;|\nTerminating server due to timeout...&quot;);
            System.out.println(&quot;Server is terminated!&quot;);
            s.close();
        }
    }
}

Client side:

package serverClient;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class ClientDemo {

    public static void main(String[] args) throws Exception {
        Socket s = new Socket(&quot;127.0.0.1&quot;, 50555);
        BufferedReader InFromServer = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String date = InFromServer.readLine();
        System.out.println(date);
        InFromServer.close();
        s.close();
    }
}

huangapple
  • 本文由 发表于 2020年8月27日 12:28:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/63609204.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定