【发布时间】:2018-11-11 15:03:40
【问题描述】:
我正在尝试执行以下操作:
一直计算我的设备的运行时间,并且每当客户连接时,他都会向他展示它,直到他断开连接。
怎么办?
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;
public class MyServer {
public static void main(String[] args) {
connectToServer();
}
static Calendar startTime = Calendar.getInstance();
static long StartTime = System.currentTimeMillis();
public static void connectToServer() {
try(ServerSocket serverSocket = new ServerSocket(9991)) {
Socket connectionSocket = serverSocket.accept();
InputStream inputToServer = connectionSocket.getInputStream();
OutputStream outputFromServer = connectionSocket.getOutputStream();
Scanner scanner = new Scanner( inputToServer, "UTF-8" );
PrintWriter serverPrintOut = new PrintWriter(
new OutputStreamWriter( outputFromServer, "UTF-8" ), true );
serverPrintOut.println("Welcome to time server ");
while(true) {
long EndTime = System.currentTimeMillis();
long Total = EndTime - StartTime;
serverPrintOut.println(Total);
System.out.println(Total);
try {
Thread.sleep(1000);
}
catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
但他只开始显示用户连接的时间
为什么?
【问题讨论】:
-
您的永远循环阻止任何其他客户端连接:在接受()之后,您必须将新客户端处理为专用线程。
-
你能告诉我怎么做吗?
标签: java server connection