gpt4 book ai didi

Java服务器socket程序一天后停止监听

转载 作者:太空宇宙 更新时间:2023-11-04 06:45:26 28 4
gpt4 key购买 nike

我有一台服务器,我在该机器上运行服务器套接字代码。我已经使用线程池来维护线程。问题是,当我启动服务器套接字时,它监听正常。但第二天我看到控制台在某种程度上暂停,并且没有监听任何 TCP 数据包。没有产生异常。java中服务器监听数据包有限制吗?我该如何解决这个问题?

服务器类

public final class Server {

private final ServerSocket serverSocket;
private final ExecutorService pool;



public Server(int port, int poolSize)
throws IOException {
serverSocket = new ServerSocket(port);
pool = Executors.newFixedThreadPool(poolSize);


System.out.println("Server running...");
runServerEngine();
}

public void runServerEngine() { // run the service
try {
while (true) {
System.out.println("user come ");
pool.execute(new Handler(serverSocket.accept()));
}
} catch (IOException ex) {
System.out.println("Error " + ex);


//pool.shutdown();
}
}

public static void main(String[] args) throws IOException {
Server server = new Server(1256, 20);//port number and pooling size
}
}

处理程序类

class Handler implements Runnable {

private Socket socket = null;
//private static Location location = new Location();


Handler(Socket socket) {
this.socket = socket;

}

private Handler() {
}
String recievedPacket = null;

@Override
public void run() {
// read and service request on socket
try {
BufferedReader in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));

while ((recievedPacket = in.readLine()) != null) {
//recievedPacket = in.readLine();
System.out.println("Recieved packate " + recievedPacket);

if (recievedPacket != null) {
try {
System.out.println("Saving function " + recievedPacket);


} catch (Exception ex) {
System.out.println(ex);
}

}

}

} catch (IOException ex) {
System.out.println(ex);
}
}
}

最佳答案

尝试关闭Handler的finally block 中的insocket以确保您的系统没有资源不足。

@Override
public void run() {
// read and service request on socket
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));

while ((recievedPacket = in.readLine()) != null) {
//recievedPacket = in.readLine();
System.out.println("Recieved packate " + recievedPacket);

if (recievedPacket != null) {
try {
System.out.println("Saving function " + recievedPacket);


} catch (Exception ex) {
System.out.println(ex);
}

}

}

} catch (IOException ex) {
System.out.println(ex);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ex) {
// No-OP
}

}

if (socket != null) {
try {
scoket.close();
} catch (IOException ex) {
// No-OP
}
}
}
}

如果您是 Java 7+,您可能想看看 try with resources .

关于Java服务器socket程序一天后停止监听,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24055947/

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