[英]How do i stop my server in java
How do i stop a server cause the ss.close()
doesn't stop the server. 我如何停止服务器导致ss.close()
无法停止服务器。 I am using the following code : 我正在使用以下代码:
public class Server {
ServerSocket ss;
boolean listening;
public void StartServer() {
try {
ServerSocket ss = new ServerSocket(7777);
listening = true;
JOptionPane.showMessageDialog(null, "Server started");
} catch (IOException ioe) {
JOptionPane.showMessageDialog(null, "Error: " + ioe);
}
while(listening) {
try {
new Session(ss.accept());
} catch(IOException ioe) {
JOptionPane.showMessageDialog(null, "Error: " + ioe);
}
}
}
public void StopServer() {
try {
ss.close();
} catch (Exception e) {}
}
}
I call the StopServer method somewhere else. 我在其他地方调用StopServer方法。 I have also tried to set listening to false. 我还尝试将监听设置为false。 Where i call the StartServer method i placed a Message Dialog to see if it continues. 我在其中调用StartServer方法的地方放置了一个消息对话框,以查看它是否继续。
private void btn_StartActionPerformed(java.awt.event.ActionEvent evt) {
lbl_Image2.setText("");
lbl_Image2.setIcon(new ImageIcon("../../Project/Images/GreenButton.png"));
lbl_Image2.setVisible(true);
btn_Start.setEnabled(false);
btn_Stop.setEnabled(true);
SV.StartServer();
JOptionPane.showMessageDialog(null, "Stopped");
}
When I try to call the StopServer()
the message dialog doesn't pop up. 当我尝试调用StopServer()
,不会弹出消息对话框。
Change ServerSocket ss = new ServerSocket(7777);
更改ServerSocket ss = new ServerSocket(7777);
to ss = new ServerSocket(7777);
到ss = new ServerSocket(7777);
. 。 The ss
variable referenced in the StopServer()
method is not the same one that is started in StartServer()
. StopServer()
方法中引用的ss
变量与StartServer()
启动的变量不同。
If u want to give control of starting/stopping the server, you have to create GUI based server in threads. 如果要控制启动/停止服务器,则必须在线程中创建基于GUI的服务器。 Because in StartServer method following while loop will not release its control called by the component (Start Button). 因为在StartServer方法中,以下while循环不会释放其由组件(“启动按钮”)调用的控件。
while(listening) {
try {
new Session(ss.accept());
} catch(IOException ioe) {
JOptionPane.showMessageDialog(null, "Error: " + ioe);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.