多播服务器和客户端通过发送对象来破解

时间:2012-01-09 17:31:02

标签: java datagram

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

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

这是以下代码: MulticastServer:

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

MulticastServerThread:

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

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

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

1 个答案:

答案 0 :(得分:0)

看起来好像服务器没有打开传入连接的服务器套接字,直到多播循环完成它 - 从而 - 由于“while(true)”而永远不会。

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