java - 如何通过网络连接(使用 Java)以 String 形式发送当前时间戳?

标签 java network-programming

我需要编写一个简单的 Java 客户端/服务器对,其中服务器将时间戳发送到任意 N 个客户端。到目前为止,我的服务器端代码(客户端只是相同类型的代码):

import java.sql.Timestamp;
import java.util.Date;

import java.net.*; 
import java.io.*; 

public class EchoServer 
{ 
    public static void main(String[] args) throws IOException 
    { 
        ServerSocket serverSocket = null; 

        try { 
            serverSocket = new ServerSocket(10007); 
        } 
        catch (IOException e) 
        { 
            System.err.println("Could not listen on port: 10007."); 
            System.exit(1); 
        } 

        Socket clientSocket = null; 
        System.out.println ("Waiting for connection.....");

        try
        { 
            clientSocket = serverSocket.accept(); 
        } 
        catch (IOException e) 
        { 
            System.err.println("Accept failed."); 
            System.exit(1); 
        } 

        System.out.println ("Connection successful");
        System.out.println ("Waiting for input.....");

        //added in TimeStamp code
        java.util.Date date= new java.util.Date();
        System.out.println(new Timestamp(date.getTime()));
        String timeString = (String)(new Timestamp(date.getTime()));

        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), 
                                      true); 
        BufferedReader in = new BufferedReader( 
            new InputStreamReader( clientSocket.getInputStream())); 

        String inputLine; 

        while ((inputLine = in.readLine()) != null) 
        { 
            System.out.println ("Server: " + inputLine); 
            out.println(inputLine + timeString ); 

            if (inputLine.equals("Bye.")) 
                break; 
        } 

        out.close(); 
        in.close(); 
        clientSocket.close(); 
        serverSocket.close(); 
    } 
} 

我收到此错误:

\TimestampServer>javac *.java EchoServer.java:40: error: inconvertible types String newshit = (String)(new Timestamp(date.getTime())); ^ required: String found: Timestamp 1 error

谢谢

最佳答案

String.valueOf(new Date().getTime())

关于java - 如何通过网络连接(使用 Java)以 String 形式发送当前时间戳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30008071/

相关文章:

java - 为数字和单词设置unicode的正则表达式

java - 如何将带有第二轴的第二条线添加到 POI 4.0.1 中的 XDDFChart?

Python多处理连接recv_bytes不返回数据

java - Selenium 等待 Ajax 内容加载 - 通用方法

java - 如何修复 javax.crypto.IllegalBlockSizeException?

java - 清理 HttpURLConnection 的正确方法

java - 如何读取服务器套接字 JAVA 中的所有 Inputstream

java - 如何在java程序(不是小程序)中获取默认代理设置?

java - 未从流中接收最终数据

java - 选中的复选框