2016-06-18 12 views
0

短いストーリー、このコードは完璧に動作しています。私はできるだけ少なくしたいと思っています。これは多才なserversocketです、私のためにはうまくいっています。私が変更したいのは、singleClientに変更することだけです。Java、マルチクライアントServertSocketをシングルに変換

クライアント#1は接続され、サーバーと通信しますが、クライアント#2は接続しようとしますが、クライアント#1はまだ接続されているため、接続できません。サーバーに接続して話をする。

今、私のコードは、すべてのクライアントが同時に接続して話すことができるという点を除いて、まったく同じことをしています。これは私が望まないものです。 P.s - クライアント側は正常に動作しています。ただ、サーバーサイドで助け、そして最後に一つ必要、私はJavaSavvyないんだけど、そうspoonfeedingが大幅に高く評価されています。これを行うには$

Socket s=null; 
      ServerSocket ss2=null; 
      Status = ("Server Listening......"); 
      try{ 
       ss2 = new ServerSocket(4445); // can also use static final PORT_NUM , when defined 

      } 
      catch(IOException e){ 
      e.printStackTrace(); 
      System.out.println("Server error"); 

      } 


      ServerThread serverThread = null; 
      while(true){ 
       try{ 
        s= ss2.accept(); 
        Status = ("connection Established"); 

        if (serverThread == null || !serverThread.isAlive()) { 
        ServerThread st=new ServerThread(s);  
        st.start(); 
        } 
        else 
         s.close(); 
       } 

      catch(Exception e){ 
       e.printStackTrace(); 
       System.out.println("Connection Error"); 

      } 
      } 

     } 




      class ServerThread extends Thread{ 


       String str = "Hello"; 
       String line=null; 
       BufferedReader is = null; 
       PrintWriter os=null; 
       Socket s=null; 

       public ServerThread(Socket s){ 
        this.s=s; 
       } 

       public void run() { 
       try { 
        BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); 
         OutputStream os = s.getOutputStream(); 
         PrintWriter pw = new PrintWriter(os, true); 
         pw.println("Hi"); 
        line=br.readLine(); 
        String input = br.readLine().replaceAll("[^A-Za-z0-9]", ""); 
        while ((input = br.readLine()) != null) { //Here is the loop part 
         input = input.replaceAll("[^A-Za-z0-9]", ""); 
         if(input.contains("Done")){ 
          System.out.println("We closing it"); 
          s.close(); 
         } 
         else if (input.equals(str)) { 
          System.out.println("We received : " + str); 
          pw.println("Hi"); 
         } 
         if (input.contains(str)){ 
           Finite(); 
         } 
         if(input.contains("Done")){ 
          System.out.println("We closing it"); 
          s.close(); 
         } 
        } 

       } catch (IOException e) { 

        line=this.getName(); //reused String line for getting thread name 
        System.out.println("IO Error/ Client "+line+" terminated abruptly"); 
       } 
       catch(NullPointerException e){ 
        line=this.getName(); //reused String line for getting thread name 
        System.out.println("Client "+line+" Closed"); 
       } 

       finally{  
       try{ 
        System.out.println("Connection Closing.."); 
        if (is!=null){ 
         is.close(); 
         System.out.println(" Socket Input Stream Closed"); 
        } 

        if(os!=null){ 
         os.close(); 
         System.out.println("Socket Out Closed"); 
        } 
        if (s!=null){ 
        s.close(); 
        System.out.println("Socket Closed"); 
        } 

        } 
       catch(IOException ie){ 
        System.out.println("Socket Close Error"); 
       } 
       }//end finally 
       } 
      } 

答えて

0

一つの方法は、変数としてServerThreadインスタンスを宣言することで、それぞれの時間新しい接続を受け入れ、このスレッドがすでにクライアントに接続されているかどうかをチェックし、ソケットを閉じることによって新しい接続を拒否するかどうかを確認します。例えば

// Keep the server thread as a variable, so we can check if it's already connected. 
ServerThread serverThread = null; 
while (true) { 
    try { 
     socket = serverSocket.accept(); 
     Status = ("Connecting accepted"); 
     if (serverThread == null || !serverThread.isAlive()) { 
      // No other client is connected, so start a new thread. 
      serverThread = new ServerThread(socket); 
      serverThread.start(); 
      System.out.println("Client connected.") 
     } else { 
      // A client is already connected, so close the socket. 
      socket.close(); 
      System.out.println("Client already connected: connection closed.") 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
     System.out.println("Connection Error"); 
    } 
} 
+0

を必要としません。サーバーに、あなたが推薦した変更の後に完全なコードを更新しました、まだ運がありません。 – BioPipeRex

+0

それは私のために働いています:2番目のクライアントが接続すると、サーバーはソケットを閉じます。何を見ていますか? 「サーバーと話す」とはどういう意味ですか? – ck1

+0

あなたのお勧め後に私のアップデートをチェックしましたか? DId私はそれを正しく行う?私が見ていることは、サーバーとすべてのクライアントが同時に話していることです。 (あなたの最後の質問に関しては、このプロジェクトは基本的に "Hello"と "Hi"によってクライアントと話す1台のサーバです。 – BioPipeRex

0

は、単純にスレッドを開始しないでください。これは、s.start()s.run()に置き換えて行うことができます。 s.run()に電話すると、サーバーコードがメインスレッドで実行されます。あなたのコードで あなたは置き換えることができます。

if (serverThread == null || !serverThread.isAlive()) { 
     ServerThread st=new ServerThread(s);  
      st.start(); 
    } 
    else 
      s.close(); 

ServerThread st=new ServerThread(s); 
    st.run(); 

によってあなたはまた、まだ2つのクライアントが話をしましょう、私のproiblemを解決していないライン

ServerThread serverThread = null; 
関連する問題