[英](Java server socket) send message every minute to a client
I'm trying to make a server (that allows multiple client requests) using java sockets.我正在尝试使用 Java 套接字创建一个服务器(允许多个客户端请求)。 My problem is that I want to make it so when a client sends a request, the server replies giving the server time once every minute.
我的问题是我想让它在客户端发送请求时,服务器每分钟回复一次给服务器时间。 And I want the server to give the time every minute eternally until the client stops the request process (for example, stoping the process in the terminal using "Ctrl+C" key combination).
而且我希望服务器永远每分钟给出一次时间,直到客户端停止请求进程(例如,使用“Ctrl+C”组合键在终端中停止进程)。 This is the code I already writed, but I'm not sure about how to implement the "give-time-each-minute loop".
这是我已经编写的代码,但我不确定如何实现“每分钟给时间循环”。 What's the better way to do it?
什么是更好的方法?
public class Server {
public static void main(String args[]) throws IOException {
final int portNumber = Integer.parseInt(args[0]);
System.out.println("Initializing server socket at port" + portNumber);
ServerSocket serverSocket = new ServerSocket(portNumber);
while (true) {
Socket socket = serverSocket.accept();
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os, true);
// Here I want to introduce code to give the client the current
// server time once each minute.
// String time = getTime();
// pw.println("Current server time is: " + time);
// ...
pw.close();
socket.close();
}
}
public String getTime(){
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String stringTime = sdf.format(date);
return stringTime;
}
}
Thank you!谢谢!
I will do like it :) 我会喜欢的:)
public class Server {
public static void main(String args[]) throws IOException {
final int portNumber = Integer.parseInt(args[0]);
System.out.println("Initializing server socket at port" + portNumber);
ServerSocket serverSocket = new ServerSocket(portNumber);
long mainTime = System.currentTimeMillis()/1000;
while (true) {
Socket socket = serverSocket.accept();
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os, true);
if((System.currentTimeMillis()/1000-mainTime)%60>1)){
String time = getTime();
pw.println("Current server time is: " + time);
}
pw.close();
socket.close();
}
}
public String getTime(){
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String stringTime = sdf.format(date);
return stringTime;
}
} }
I guess for this purpose node.js will be helpful. 我想为此目的,node.js会有所帮助。 because for consistent connection and to handle multiple request at a time node.js works better then any other language.
因为为保持一致的连接并同时处理多个请求,node.js的效果比其他任何语言都要好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.