我有Server(Socket),它将消息分发到与其连接的每个客户端。
在客户端,我每秒打印一次从服务器接收到的消息数。
当第二个客户端连接到服务器时,服务器发送了比以前更多的消息。
有人知道为什么会这样吗?
请尝试运行它,如果它也发生在我身上,请告诉我。谢谢。
我以为是因为我的机器规格和Java版本。
我尝试过:
Java 8,11,12
机器规格:
逻辑处理器:4
核心数:4
我也在只有一个处理器的机器上尝试过。
服务器:
public class Server implements Runnable {
private final static int PORT = 465;
private OutputStream os;
private Server(OutputStream os) {
this.os = os;
}
public static void main(String[] args) throws IOException {
final ServerSocket server = new ServerSocket(PORT);
//noinspection InfiniteLoopStatement
while (true) {
Socket client = server.accept();
System.out.println(client.toString());
Thread worker = new Thread(new Server(client.getOutputStream()));
worker.start();
}
}
@Override
public void run() {
try {
byte[] response = "dummy message".getBytes();
//noinspection InfiniteLoopStatement
while (true) {
os.write(response);
}
} catch (IOException ignored) {
}
}
}
客户:
public class Client extends Thread {
private final static String HOST = "localhost";
private final static int PORT = 465;
private final static SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss.SSS");
public static void main(String[] args) throws IOException {
Socket socket = new Socket(HOST, PORT);
DataInputStream dis = new DataInputStream(socket.getInputStream());
byte[] msg = new byte[13]; // "dummy message".length
int msgCount = 0;
long timeLimit = System.currentTimeMillis();
System.out.println("-----------: #_msg");
//noinspection InfiniteLoopStatement
while (true) {
dis.readFully(msg);
msgCount++;
boolean elapsed = System.currentTimeMillis() >= timeLimit;
if (elapsed) {
timeLimit = System.currentTimeMillis() + 1000;
System.out.println(dateFormat.format(new Date()) + ": " + msgCount);
msgCount = 0;
}
}
}
}