JAVA——关闭ServerSocket
問(wèn)題描述
accept()方法無(wú)限循環(huán)內(nèi)的阻塞,無(wú)法退出while循環(huán)。
API
public?Socket?accept() throws IOException
偵聽(tīng)要連接到此套接字并接受它。 該方法將阻塞直到建立連接。
創(chuàng)建一個(gè)新的Socket s ,如果有安全管理器,則使用s.getInetAddress().getHostAddress()和s.getPort()作為其參數(shù)來(lái)調(diào)用安全管理器的checkAccept方法,以確保允許操作。 這可能會(huì)導(dǎo)致SecurityException。
結(jié)果
新的Socket
異常
IOException - 如果在等待連接時(shí)發(fā)生I / O錯(cuò)誤。
SecurityException - 如果安全管理器存在,并且其 checkAccept方法不允許操作。
SocketTimeoutException - 如果先前使用setSoTimeout設(shè)置了超時(shí)并且達(dá)到超時(shí)。
IllegalBlockingModeException - 如果此套接字具有關(guān)聯(lián)的通道,則該通道處于非阻塞模式,并且沒(méi)有準(zhǔn)備接受的連接
另請(qǐng)參見(jiàn):
SecurityManager.checkAccept(java.lang.String, int)
public?void?setSoTimeout(int?timeout) throws SocketException
啟用/禁用SO_TIMEOUT帶有指定超時(shí),以毫秒為單位。 使用此選項(xiàng)設(shè)置為非零超時(shí),對(duì)此ServerSocket的accept()的調(diào)用將僅阻止此時(shí)間。 如果超時(shí)超時(shí), 則會(huì)引發(fā)java.net.SocketTimeoutException ,盡管ServerSocket仍然有效。 必須先啟用該選項(xiàng)才能進(jìn)入阻止操作才能生效。 超時(shí)時(shí)間必須為> 0 。 超時(shí)為零被解釋為無(wú)限超時(shí)。
參數(shù)
timeout - 指定的超時(shí),以毫秒為單位
異常
SocketException - 如果底層協(xié)議有錯(cuò)誤,如TCP錯(cuò)誤。
從以下版本開(kāi)始:
JDK1.1
另請(qǐng)參見(jiàn):
getSoTimeout()
解決方案
使用Timeout(int?timeout) 設(shè)置超時(shí)時(shí)間
設(shè)置ServerSocket是否開(kāi)啟監(jiān)聽(tīng)標(biāo)記
package netchat; import java.io.*; import java.net.*; import javax.swing.JTextArea; public class NetSocket {private ServerSocket ssk;private boolean isStop;public NetSocket() {isStop=false;ssk=null;}/*** @param port 監(jiān)聽(tīng)端口* @throws IOException 如果發(fā)生I / O錯(cuò)誤*/public void startReceive(int port) throws IOException{// TODO 自動(dòng)生成的方法存根ssk = new ServerSocket(port);isStop=false;ssk.setSoTimeout(5*10000);new Thread(()-> {while(!isStop) {Socket sk=null;try {sk = ssk.accept();} catch (IOException e) {// TODO 自動(dòng)生成的 catch 塊e.printStackTrace();}new Thread(new ReceiveThread(sk)).start();}try {ssk.close();} catch (IOException e) {// TODO 自動(dòng)生成的 catch 塊e.printStackTrace();}}).start();}/*** Close ReceiveThread*/public void stopReceive() {// TODO 自動(dòng)生成的方法存根isStop=true;} }?
參考文章
https://bbs.csdn.net/topics/250016069
https://blog.csdn.net/budapest/article/details/6941903
https://blog.csdn.net/weixin_41715077/article/details/88791499
總結(jié)
以上是生活随笔為你收集整理的JAVA——关闭ServerSocket的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Windows——蓝屏[失败的操作:Ha
- 下一篇: 使用鼠标控制手机