我实际上在编写必须使用UDP服务器的代码。在我的应用程序生命周期内,我必须关闭该服务器,并能够在以后重新打开它。问题是,服务器在监听时存货很大,因此我通过过早关闭服务器套接字来强制关闭服务器。显示此异常:
java.net.SocketException: Socket closed
at java.net.PlainDatagramSocketImpl.receive0(Native Method)
at java.net.AbstractPlainDatagramSocketImpl.receive(AbstractPlainDatagramSocketImpl.java:143)
at java.net.DatagramSocket.receive(DatagramSocket.java:812)
at test.UdpServer.run(UdpServer.java:21)
at java.lang.Thread.run(Thread.java:748)
这是我的MCVE:
主要:
package test;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class test {
private static Thread server, display;
private static UdpServer udpServer = new UdpServer();
public static void main(String args[]){
display = new Thread() {
public void run() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton start = new JButton("start");
JButton stop = new JButton("stop");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
panel.add(start);
panel.add(stop);
frame.setContentPane(panel);
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
server = new Thread(udpServer);
server.start();
}
});
stop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
udpServer.stopReception();
}
});
frame.pack();
frame.setVisible(true);
}
};
display.start();
}
}
服务器:
package test;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UdpServer implements Runnable {
private boolean run;
private DatagramSocket serverSocket;
public void run() {
run = true;
try {
serverSocket = new DatagramSocket(8000);
byte[] receiveData = new byte[1024];
while(run){
System.out.println("Waiting for command : ");
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
if(run) {
receiveData = receivePacket.getData();
String message = new String (receivePacket.getData());
System.out.println(message);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void stopReception() {
run = false;
serverSocket.close();
}
}
我做了一些重新研究,发现类似的thread,但我不明白user207421在解释
关闭它们以进行输入。
所以我的问题是,如何在不引发异常的情况下强制关闭套接字?
引发此异常真的有问题吗?因为我的应用程序的寿命没有受到影响,并且此后可以重新打开服务器。