gpt4 book ai didi

java - 使用线程池创建一个等待来自客户端的消息的java服务器套接字

转载 作者:行者123 更新时间:2023-12-02 08:49:51 26 4
gpt4 key购买 nike

@FXML
private TextArea textarea;
@FXML
private ImageView imagev;

@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
Serverth Server = new Serverth();
Server.start();
}


class Serverth extends Thread {
@Override
public void run() {
try {
final int NUM_THREAD = 99;


ServerSocket socket = new ServerSocket(8078);
ExecutorService exec = Executors.newFixedThreadPool(NUM_THREAD);
System.out.println("SERVER SOCKET CREATED");


while (!isInterrupted()) {
Socket in = socket.accept();
Runnable r = new ThreadedHandler(in);
exec.execute(r);

}
} catch (IOException e) {
System.out.println(e.getMessage());
}

}
}

class ThreadedHandler implements Runnable {

private Socket incoming;

public ThreadedHandler(Socket in) {
incoming = in;
}

public void run() {
try {
try {
ObjectInputStream is=new ObjectInputStream(incoming.getInputStream());

while(true) {
if (is.available() > 0) {
String line = is.readUTF();

textarea.appendText("\n" + "[" + new java.util.Date() + "] : " + line);

if (line.contains("inviato")) {
Object obj = is.readObject();
Email ema = (Email) obj;
try {
SimpleDateFormat formatter = new SimpleDateFormat("dd-M-yyyy-hh-mm-ss");
FileOutputStream fileOut = new FileOutputStream("src/Server/" + ((Email) obj).getDestinat() + "/" + formatter.format(((Email) obj).getData()) + ".txt");
ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(ema);
objectOut.flush();
objectOut.close();
System.out.println("The Object was succesfully written to a file");

} catch (Exception ex) {
ex.printStackTrace();
}

}

}
}
} catch(IOException ex) {
ex.printStackTrace();
}

} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
incoming.close();
} catch (IOException ex) {
ex.printStackTrace();
}

}
}
}

在 run 方法(在 Serveth 类中)内,我创建一个服务器套接字并调用 exec.execute 方法。在 run 方法(在 ThreadedHandler 类中)内,服务器正在等待来自客户端的消息(在这种特定情况下,它会创建一个新的 .txt 文件,但这并不重要)。一切正常,但会导致 CPU 过度使用和延迟!!!

最佳答案

InputSteam.available 方法立即返回一个值,告诉您没有可供读取的字节,因此此代码运行一个非常“热”的自旋循环:

            while(true) {
if (is.available() > 0) {
...
}
}

available 方法很少有用,并且经常给出令人困惑的结果(例如,参见 inputstream.available() is 0 always )。我建议您完全删除 if 语句:

            while(true) {
String line = is.readUTF();

textarea.appendText("\n" + "[" + new java.util.Date() + "] : " + line);
...
}

您的代码无法正常退出循环。您可能想要添加一种机制让客户端与服务器断开连接。

关于java - 使用线程池创建一个等待来自客户端的消息的java服务器套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60850504/

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