2017-01-18 5 views
-1

これは問題文です。Chatterサーバーとクライアント

サーバーが2つのチャットクライアントと一致するようにするプロトコルを設計します。サーバーは、今後の接続のためにTCPポートをリッスンします。クライアントがすでにペアになるサーバーに接続していない場合、サーバーは接続しているクライアントを受け入れ、別のクライアントを待機させます。これを行うために、接続するクライアントにメッセージを送信して待機させます。このコマンドを受け取ると、クライアントは別のServer Socketインスタンスを構築し、ポートで待機します。次に、クライアントは、新しく作成されたサーバーがリッスンするポート番号を含むサーバーにmesaggeを送信します。 C1が待機している間に別のクライアントC2がサーバとの接続を試みると、サーバはC2にメッセージ「PEER_LOC $ h:$ p」を送信することによってC1の存在をC2に通知します。ここで、$ hはホスト名(またはIPアドレス)であり、$ pはC1が待機しているポート番号です。 C2はこのメッセージを受信すると、取得した情報を使用してC1への接続を求めます。クライアントはユーザーからのメッセージを受け取ります。 2人のクライアントはどちらか一方の側がストリームの終わりを送るまでメッセージを交換します "(LinuxではCtrl-D)。それらの保全はその後終了します。高度な方法は複数のスレッド、タイムアウトなどを使用することがあり、この問題では必要ありません。

私の問題は、2つのクライアントをサーバーに接続することです。私は、私のサーバープログラムを実行し、次に別の名前だけでお互いに複製されている2つの他のクライアントクラスを実行します。私はそれらのうちの1つに接続することができ、他のものだけが永遠に待つように見える。

私のクラスです。

サーバー:

package chatserver2; 

import java.io.*; 
import java.net.*; 
import java.awt.*; 
import java.awt.event.*; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import javax.swing.*; 
    // import all the class that you will need for functionailty 

// extends jframe to develop gui's in java 
public class Server { 

    private static ObjectOutputStream output; // stream data out 
    private static ObjectInputStream input; // stream data in 
    private static ServerSocket server; 
    private static Socket connection; // socket means set up connetion between 2 computers 

    private static int n; 

//Constructor 
    public static void main(String[] args) throws IOException { 

     Server obj = new Server(); 
     obj.RunServer(); 

     try { 
      while (true) { 

       Handler obj2 = new Handler(); 

       obj2.start(); 
       System.out.println("Accepted connection from " 
         + connection.getInetAddress() + " at port " 
         + connection.getPort()); 

       n++; 
       System.out.println("Count " + n); 
      } 
     } finally { 
      connection.close(); 
     } 

    } 

    public Server() { 

    } 

// run the server after gui created 
    public void RunServer() { 

     try { 
      server = new ServerSocket(6789); // 1st number is port number where the application is located on the server, 2nd number is the amount of people aloud to connect 
      while (true) { 

       try { 
        waitForConnection(); // wait for a connection between 2 computers 
        setupStreams(); // set up a stream connection between 2 computers to communicate 
        whileChatting(); // send message to each other 
        // connect with someone and have a conversation 
       } catch (EOFException eofException) { 

       } 
      } 
     } catch (IOException ioException) { 

      ioException.printStackTrace(); 
     } 
    } 

//Wait for a connection then display connection information 
    private void waitForConnection() { 

     try { 
      connection = server.accept(); 
     } catch (IOException ioexception) { 

      ioexception.printStackTrace(); 
     } 

    } 
    // stream function to send and recive data 

    private void setupStreams() throws IOException { 

     output = new ObjectOutputStream(connection.getOutputStream()); // set up pathway to send data out 
     output.flush(); // move data away from your machine 
     input = new ObjectInputStream(connection.getInputStream()); // set up pathway to allow data in 

    } 

// this code while run during chat conversions 
    private void whileChatting() throws IOException { 

     String message = "WAIT "; 
     sendMessage(message); 

     do { 

      try { 

       message = (String) input.readObject(); // stores input object message in a string variable 

       System.out.println("Message from Client " + message); 
      } catch (ClassNotFoundException classnotfoundException) { 

      } 
     } while (!message.equals("CLIENT - END"));// if user types end program stops 

    } 

    private void closeChat() { 

     try { 

      output.close(); 
      input.close(); 
      connection.close(); 

     } catch (IOException ioexception) { 

      ioexception.printStackTrace(); 
     } 
    } 

// send message to the client 
    private void sendMessage(String message) { 

     try { 

      output.writeObject(message); 
      output.flush(); 

      System.out.println("Message to client " + message); 

     } catch (IOException ioexception) { 

     } 

    } 

    public static class Handler extends Thread { 

     private Socket connection; 

     public Handler() { 

      String message = "WAIT"; 

     } 

     public void run() { 

      System.out.println("Connect" + Server.connection); 
      while (true) { 

       try { 
        waitForConnection(); 
        setupStreams(); 
        whileChatting(); 
       } catch (IOException ex) { 
        Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex); 
       } 

      } 

     } 

     private void waitForConnection() { 

      System.out.println("server" + server); 
      try { 
       connection = server.accept(); 
      } catch (IOException ioexception) { 

       ioexception.printStackTrace(); 
      } 
      System.out.println("Connection" + connection); 

     } 

     private void setupStreams() throws IOException { 

      output = new ObjectOutputStream(connection.getOutputStream()); // set up pathway to send data out 
      output.flush(); // move data away from your machine 
      input = new ObjectInputStream(connection.getInputStream()); // set up pathway to allow data in 

     } 

     private void whileChatting() throws IOException { 

      String message = " You are now connected "; 
      sendMessage(message); 

      do { 

       try { 

        message = (String) input.readObject(); 

       } catch (ClassNotFoundException classnotfoundException) { 

       } 
      } while (!message.equals("CLIENT - END")); 

     } 

     private void closeChat() { 

      try { 

       output.close(); 
       input.close(); 
       connection.close(); 

      } catch (IOException ioexception) { 

       ioexception.printStackTrace(); 
      } 
     } 

     static private void sendMessage(String message) { 

      try { 

       output.writeObject(message); 
       output.flush(); 

      } catch (IOException ioexception) { 

      } 

     } 

    } 
} 

ザ・と1つの重複クライアントクラスC1、またはC2:

package chatserver2; 

import java.io.*; 
import java.net.*; 
import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 
    // import all the class that you will need for functionailty 

// extends jframe to develop gui's in java 
public class Client1 extends JFrame { 

    private JTextField userInput; // 
    private JTextArea theChatWindow; // 
    private ObjectOutputStream output; // stream data out 
    private ObjectInputStream input; // stream data in 

    private Socket connection; // socket means set up connetion between 2 computers 

//Constructor 
    public Client1() { 

    } 

// run the server after gui created 
    public void RunClient() { 

     try { 
      connection = new Socket("localhost", 6789);// 1st number is port number where the application is located on the server, 2nd number is the amount of people aloud to connect 
      while (true) { 

       try { 
        // wait for a connection between 2 computers 
        setupStreams(); // set up a stream connection between 2 computers to communicate 
        whileChatting(); // send message to each other 
        // connect with someone and have a conversation 
       } catch (EOFException eofException) { 

       } finally { 

        closeChat(); 
       } 
      } 
     } catch (IOException ioException) { 

      ioException.printStackTrace(); 
     } 
    } 

//Wait for a connection then display connection information 
    // stream function to send and recive data 
    private void setupStreams() throws IOException { 

     output = new ObjectOutputStream(connection.getOutputStream()); // set up pathway to send data out 
     output.flush(); // move data away from your machine 
     input = new ObjectInputStream(connection.getInputStream()); // set up pathway to allow data in 

    } 

// this code while run during chat conversions 
    private void whileChatting() throws IOException { 

     String message = ""; 

     do { 
      // have conversion while the client does not type end 
      try { 

       message = (String) input.readObject(); // stores input object message in a string variable 
       System.out.println("message " + message); 
       if (message.equals("WAIT")) { 
        ServerSocket server2 = new ServerSocket(5000); 
        System.out.println("Hello"); 
        message = "5000"; 
        sendMessage(message); 

       } 
       System.out.println("From server " + message); 

      } catch (ClassNotFoundException classnotfoundException) { 

      } 
     } while (!message.equals("CLIENT - END"));// if user types end program stops 

    } 

    private void closeChat() { 

     try { 

      output.close(); // close output stream 
      input.close(); // close input stream 
      connection.close(); // close the main socket connection 

     } catch (IOException ioexception) { 

      ioexception.printStackTrace(); 
     } 
    } 

// send message to the client 
    private void sendMessage(String message) { 

     try { 

      output.writeObject(" - " + message); 
      output.flush(); // send all data out 

     } catch (IOException ioexception) { 

      theChatWindow.append("\n ERROR: Message cant send"); 
     } 

    } 

// 
// 
    public static void main(String[] args) { 
     Client1 obj = new Client1(); 
     obj.RunClient(); 
    } 

} 

私は2番目のクライアントは、いつまでも待って実行する最初のクライアントに接続することができます。何か提案やコメントをいただければ幸いです。

+0

あなたは 'accept'型のループではありませんので、どのように複数のクライアント接続を受け入れることができますか? –

+0

ああ、私はあなたが2つの場所にコードを持っていることを確認します '受け入れる' –

+0

それはwhileループではありません。私はwhileメソッドを呼び出している間に呼び出します? – user7338821

答えて

1

ハンドラ(Runnableを実装し、スレッドを拡張する必要はありません)は、サーバが接続するたびに独自のバックグラウンドスレッドで作成して実行する必要があります。次の接続を行います。私はあなたがなぜ最初にwhile (true)ループを持っているのか分かりません。何も役に立たないからです。すべての重要なコードは2番目の真のループにあり、1つはrunServer()にあり、これがハンドラを作成する場所です。

+0

だから、whileConnectedメソッドでhandlerのインスタンスを作成する必要があります。つまり、server.accept(port)はどこですか? – user7338821

+0

私は通常、acceptから取得したSocketオブジェクトを取得し、それをHandlerのコンストラクタに渡してから、スレッド内でハンドラを実行します。 'new Thread(new MyHandler(myAcceptedSocket))。start();' –

+0

@ user7338821:Clientクラスは1つだけ必要です。はい、このクラスの2つのインスタンスが必要ですが、1つのクラスだけが必要です。 –

関連する問題