0

サーバーのIPを受信すると、そのIPをマルチキャストグループに送信し、グループ内のクライアントがオブジェクトを送信するマルチキャストサーバーを実装しています。そして、これは定期的に行われます。

したがって、最初の接続は 1 対多で、2 番目の接続は 1 対 1 です。個々の部分、つまりマルチキャストを実装し、オブジェクトをソケット経由で正しく送信しましたが、全体として実行するとエラーに直面しています。

コードは次のとおりです。

public class MulticastServer {
public static void main(String[] args) throws java.io.IOException {
new MulticastServerThread().start();
}
}

マルチキャスト サーバー スレッド:

public class MulticastServerThread extends QuoteServerThread {
public void run() {
while (true) {
  try {
    byte[] buf = new byte[256];

    // construct quote
    String dString = InetAddress.getLocalHost().toString();
    buf = dString.getBytes();
InetAddress group = InetAddress.getByName("230.0.0.1");
    DatagramPacket packet = new DatagramPacket(buf, buf.length,
                                               group, 4446);

    // server join group。
    socket.send(packet);

    // sleep for a while
    try {
      sleep((long)(Math.random() * FIVE_SECONDS));
    } catch (InterruptedException e) { }

  } catch (IOException e) {
    e.printStackTrace();
    moreQuotes = false;
  }
}

socket.close();
//Sending the object
 try {
    ServerSocket ss = new ServerSocket(port);
    Socket s = ss.accept();
    InputStream is = s.getInputStream();
    ObjectInputStream ois = new ObjectInputStream(is);
    Object to = (Object)ois.readObject();
    if (to!=null){System.out.println(to.a);}
    System.out.println((String)ois.readObject());
    is.close();
    s.close();
    ss.close();
}catch(Exception e){System.out.println(e);}
}
}

QuoteServerThread:

public class QuoteServerThread extends Thread {
protected DatagramSocket socket = null;
protected BufferedReader in = null;
protected boolean moreQuotes = true;
private static int TTL = 128;
int port=2002;
//Code which returns the IP of the server
}
}

クライアント側: MulticastClient:

public class MulticastClient {
public static void main(String[] args) throws IOException {
MulticastSocket socket = new MulticastSocket(4446);
InetAddress address = InetAddress.getByName("230.0.0.1");
socket.joinGroup(address);

DatagramPacket packet;

// get a few quotes
boolean Condition=true;
while(Condition) {
  byte[] buf = new byte[256];
  packet = new DatagramPacket(buf, buf.length);
  socket.receive(packet);

  String received = new String(packet.getData());
  System.out.println("IP of controller" + received);

  Socket s=new Socket("localhost",2002);
  ObjectOutputStream os=(ObjectOutputStream) s.getOutputStream();
  ObjectOutputStream oos=new ObjectOutputStream(os);
  Object to=new Object();
  oos.writeObject(to);
  oos.writeObject(new String("another object from client"));
  oos.close();
  os.close();
  s.close();
}

socket.leaveGroup(address);
socket.close();
}

クライアント側のソケット作成を指すスレッド「メイン」で例外が発生しています。

誰か助けてくれませんか?ありがとう!

4

1 に答える 1

0

マルチキャスト ループが完了するまで、サーバーは着信接続用にサーバー ソケットを開いていないように見えますが、「while(true)」が原因で、これは決して行われません。

マルチキャスト用に 1 つのスレッドを開始し、(少なくとも) 着信接続用に 1 つのスレッドを開始して、それらが別々に動作できるようにする必要があります。

于 2012-01-09T17:41:52.353 に答える