gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:42:40 27 4
gpt4 key购买 nike

我需要编写一个简单的 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com