2013-10-03 136 views
1

問題:Java Socket技術編程

我寫了一個java的插槽服務器其中發送響應,當我第一次發送消息從客戶到它。但我想根據第一個響應發送一條消息。第一個迴應後,我沒有得到任何其他答覆?

這裏是服務器代碼:

public class SendSmsServerSocket { 

    private final static CxpsLogger logger = CxpsLogger.getLogger(SendSmsServerSocket.class); 

    SendSmsServerSocket(){ 
     try { 
      new SeverSocketForSms(new ServerSocket(4330)); 
     } catch (IOException e) { 
     e.printStackTrace(); 
     } 

    } 
} 


private static class SeverSocketForSms extends Thread { 

    private Socket socket; 
    private ServerSocket serversocket; 
    private volatile static boolean running = true; 

    public SeverSocketForSms(ServerSocket ssocket) throws IOException { 
     this.serversocket = ssocket; 
     start(); 
    } 

    public void run() { 
     try{ 
     while(running) { 
      this.socket = serversocket.accept(); 
      InputStreamReader ir = new InputStreamReader(socket.getInputStream()); 
      BufferedReader br = new BufferedReader(ir); 
      String msg = br.readLine(); 

      PrintStream ps = new PrintStream(socket.getOutputStream()); 
      ps.println("inside SeverSocketForSms: msg received is : "+msg); 
     } 


     } 
     catch(Exception e){ 
     e.printStackTrace(); 
     } 
     catch(Throwable t) { 
     System.out.println("Caught " + t + "xmlServerThread - closing thread"); 
     } 
    } 

    public static void shutdown() { 
     System.out.println("Stopping socket connection and thread"); 
     try{ 
      socket.close(); 
     }catch (Exception e) { 
      e.printStackTrace(); 
     } 
     running = false; 
    } 



    public static void main (String [] args){ 
     try { 
      System.out.println("Starting sms server ----- Please press Enter Key to stop the server after receiving one message"); 
      SendSmsServerSocket s=new SendSmsServerSocket(); 

      new Scanner(System.in).nextLine(); 
      SeverSocketForSms.shutdown(); 


     } catch (Exception e) { 
      e.printStackTrace(); 
     } 



    } 
} 

回答

1

一旦你有一個傳入連接,您應該delgate處理傳入的連接到另外Thread責任,否則就會阻止你的「接受」線程,直到當前連接被關閉...

while (running) { 
    this.socket = serversocket.accept(); 
    Thread thread = new Thread(new Handler(socket)); 
    thread.start(); 
} 

而且Handler

public class Handler implements Runnable { 
    private Socket socket; 
    public Handler(Socket socket){ 
     this.socket = socket; 
    } 

    public void run() { 
     // You may need to add a repeat and exit clause here... 
     InputStreamReader ir = new InputStreamReader(socket.getInputStream()); 
     BufferedReader br = new BufferedReader(ir); 
     String msg = br.readLine(); 

     PrintStream ps = new PrintStream(socket.getOutputStream()); 
     ps.println("inside SeverSocketForSms: msg received is : " + msg); 
    } 
} 
+0

最好使用線程池,而不是爲每個請求創建一個線程。 – xfeep

+0

@xfeep這是真的 – MadProgrammer