gpt4 book ai didi

java - 客户端-服务器聊天中的客户端 CPU 负载 30-50%

转载 作者:太空宇宙 更新时间:2023-11-04 13:20:13 24 4
gpt4 key购买 nike

客户端连接到服务器,服务器向客户端发送1条消息,客户端必须等待另一条消息。当客户端在 while(true) 循环中等待时,它会将 CPU 加载到 50%。我尝试尽可能简单地做到这一点,以了解它是如何工作的。

附注所有 catch() 都已隐藏,以最大限度地减少此处的代码。

客户:

public class SocketClient 
{
String host;
int port;
static Socket connection;
BufferedReader bfr;

public SocketClient(String host, int port)
{
this.port = port;
this.host = host;
}

public void connect() throws UnknownHostException, IOException, Exception
{
connection = new Socket(new String(host), port);
System.out.println("Client is ready.");

bfr = new BufferedReader(new InputStreamReader(connection.getInputStream()));
}

public void readInput() throws IOException
{
String input;
if(input = bfr.readLine()) != null)
{
System.out.println(input);
}
}

public static void main(String[] args) throws UnknownHostException, IOException, Exception
{
SocketClient socketClient = new SocketClient("localhost", 19999);

try {
socketClient.connect();

try
{
while(true)
{
socketClient.readInput();
}
}

}
}
}

服务器:

   public class MultipleSocketServer implements Runnable {

private Socket connection;
private String TimeStamp;
private int ID;

static PrintWriter writer;
private static File file;

public static void main(String[] args)
throws FileNotFoundException, UnsupportedEncodingException
{

int port = 19999;
int count = 0;

file = new File("E:/test.txt");
writer = new PrintWriter(file, "UTF-8");

try
{
ServerSocket socket = new ServerSocket(port);
System.out.println("MultipleSocketServer Initialized");

while (true)
{
Socket connection = socket.accept();
Runnable runnable = new MultipleSocketServer(connection, ++count);
Thread thread = new Thread(runnable);
thread.start();
}
}
}


MultipleSocketServer(Socket s, int i) {
this.connection = s;
this.ID = i;
}

public void run() {
try {

System.out.println("Connected: " + connection.getLocalSocketAddress() + " at port " + connection.getPort());
writer.println(ID + ": " + connection.getLocalSocketAddress() + " at port " + connection.getPort());
writer.flush();


BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
writer.write("MultipleSocketServer repsonded at " + new java.util.Date().toString());
writer.write("\n");
writer.flush();

}
finally {
try {
connection.close();
}
}
}
}

最佳答案

分析

看来服务器端在发送数据后关闭了连接。

客户端有如下无限循环:

while (true)
{
socketClient.readInput();
}

循环会导致CPU消耗:bfr.readLine()方法调用将在连接关闭后立即返回null

解决方案

请考虑将客户端的循环更改为读取直到“连接结束”:

String input;
while ((input = bfr.readLine()) != null) {
System.out.println(input);
}

关于java - 客户端-服务器聊天中的客户端 CPU 负载 30-50%,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33136565/

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