我有這段代碼可以讓服務器在一個執行緒中運行。保持服務器打開的目的是我想通過這個服務器通過靜態方法向客戶端發送一些東西。
這是執行緒:
public class SampleThread extends Thread {
static PrintWriter out;
public void run() {
while(true) {
try(
ServerSocket server = new ServerSocket(SAMPLE_PORT);
Socket socket = server.accept();
){
out = new PrintWriter(socket.getOutputStream());
while(true) {
//nothing, just keeps the server running (is this working?)
}
}catch (IOException e){
//JDialog message that says retrying to connect
}
}
}
}
這是使用服務器向客戶端發送內容的靜態方法:
static void sendToClient(String s1, String s2){
out.write(s1 "\n");
out.write(s2 "\n");
out.flush();
}
當涉及到通過方法呼叫從服務器向客戶端發送內容的目的時,它可以作業。但是,如果我關閉客戶端的連接,上面的程式就不能拋出 IOException。out.write() 方法甚至根本沒有拋出任何錯誤,它只是接受我傳遞給它的任何內容。
我該怎么做才能使客戶端關閉連接后仍會觸發catch(IOException e)?
uj5u.com熱心網友回復:
沒關系。在空的 while(true){} 塊中添加一個讀取的套接字輸入就可以了。
這是我在上面添加的內容:
socket.getInputStream().read();
然后在 catch 塊上我添加了一個 out = null:
catch (IOException e){
//JDialog message that says retrying to connect
out = null;
}
之后,我只需要在執行靜態方法中的內容之前檢查是否 out != null :
static void sendToClient(String s1, String s2){
if(out != null) {
out.write(s1 "\n");
out.write(s2 "\n");
out.flush();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/488800.html
