2013-11-23 219 views
0

我正在製作一個程序,每次客戶端從服務器接收數據時都需要更新UI。爲此,socket和serversocket必須每次都關閉並重新打開。當程序嘗試接受新的連接。雖然,這是我的代碼和錯誤:嘗試重新打開連接時發生套接字關閉錯誤

public void startServer(){ 
    Thread serverstart = new Thread(){ 
     public void run() { 
       try {  
        serversocket = new ServerSocket(socket); 

        while(true){ 
         skt = serversocket.accept(); 
         close.setEnabled(true); 
         new Thread(new newClient(skt)).start(); 
        } 
      } catch (IOException e){ 
       e.printStackTrace(); 
       } 
     } 
    };serverstart.start(); 
} 
static class newClient implements Runnable { 
    private Socket socket; 
    static PrintStream output; 
    public newClient(Socket skt){ 
     this.socket = skt; 
    } 
    @Override 
    public void run(){ 
     try { 
     output = new PrintStream(socket.getOutputStream()); 
     } catch(IOException ioe){ 
      ioe.printStackTrace(); 
     } 
    } 
} 

    public void sendData(){     
     tallydata = Integer.toString(preview) + " " + Integer.toString(program);   
       System.out.println(tallydata); 
       newClient.output.print(tallydata); 

     try{ 
       skt.close(); 
       serversocket.close(); 
      } catch(IOException e){ 
       e.printStackTrace(); 
      } 
      startServer();     
    } 

插座是在送出數據()方法和startserver的()方法結束時關閉被稱爲重啓之後再次連接。這是錯誤:

java.net.SocketException: Socket closed 
    at java.net.PlainSocketImpl.socketAccept(Native Method) 
    at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:398) 
    at java.net.ServerSocket.implAccept(ServerSocket.java:522) 
    at java.net.ServerSocket.accept(ServerSocket.java:490) 
    at TallySystem.servergui$1.run(servergui.java:201) 

謝謝。

回答

0

爲什麼要關閉並重新打開服務器呢?只需啓動一次,然後保持獨立。多數民衆贊成它應該如何使用。

無論如何,每ServerSocket documentation

public void close()

Closes this socket. Any thread currently blocked in accept() will throw a SocketException.

那正是你的問題。您正忙於等待連接時關閉ServerSocket。

相關問題