0

我正在实现一个多播服务器,它将其 IP 发送到多播组,并且组中的客户端在收到服务器的 IP 后,向它发送一个对象。这是定期进行的。

因此,第一个连接是一对多,第二个是一对一。我已经实现了各个部分,即多播,正确地通过套接字发送对象,但是当我整体运行它时遇到错误。

下面是代码: MulticastServer:

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);}
}
}

报价服务器线程:

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();
}

我在线程“main”java.net.ConnectException 中遇到异常:客户端的 java.net.PlainSocketImpl.socketConnect(Native Method) 连接被拒绝,它指向客户端的套接字创建。

有人可以帮帮我吗?谢谢!

4

1 回答 1

0

看起来服务器似乎没有为传入连接打开服务器套接字,直到多播循环完成,它 - afaict - 由于“while(true)”而永远不会这样做。

您应该为多播启动一个线程,并且(至少)为传入连接启动一个线程,以便它们可以单独运行。

于 2012-01-09T17:41:52.353 回答