日期:2014-05-20  浏览次数:20775 次

关于IP组播客户端运行总是卡死的问题,各位大神帮帮忙!急!
public static void main(String args[]) {

  java.awt.EventQueue.invokeLater(new Runnable() {

  public void run() {
  try 
  {
  new Client().setVisible(true);
  MulticastClient.IP = "228.5.6.7"; //组播IP地址
  MulticastClient.toIPAddr();
  MulticastClient.port = 6789;
  MulticastClient.localHost = InetAddress.getLocalHost();
  lb.setText("本机IP地址:"+MulticastClient.localHost.getHostAddress());
  MulticastSocket mulSocket = new MulticastSocket(MulticastClient.port); 
  InetAddress mulGroup = InetAddress.getByAddress(MulticastClient.IPAddr); //组播IP地址
  byte[] buf = new byte[1000];
  DatagramPacket packet = new DatagramPacket(buf, buf.length);
   
  mulSocket.joinGroup(mulGroup); //加入组
  mulSocket.receive(packet); //接收数据包
  msg = new String(packet.getData(), 0, packet.getLength()); //提取数据包里的信息
   
  //如果是“quit”指令则终止程序,否则输出消息
  while (msg.compareTo("quit") != 0)
  {
  tb_output.setValueAt(msg, i, 0);
  mulSocket.receive(packet); //继续接收数据
  msg = new String(packet.getData(), 0, packet.getLength());
  i++;
  }
   
  tb_output.setValueAt("直播结束,谢谢观看!", i, 0);
  mulSocket.leaveGroup(mulGroup);
  mulSocket.close(); //关闭套接字
  i = 0;
  } 
  catch (IOException ex) 
  {
  ex.printStackTrace();
  }
  }
  });
  }


问题出在mulSocket.receive(packet)上面,不知如何修改


------解决方案--------------------
class MessageReciveListener {
public void onRecive(Object msg){
//Do something
}
}
MessageReciveListener msgListener = new MessageReciveListener();
new Thread() {
@Override
public void run(){
while(true) {
mulSocket.receive(packet); //接收数据包
msg = new String(packet.getData(), 0, packet.getLength()); //提取数据包里的信息
msgListener.onRecive(msg);
}
}
}.start();

差不多这样,注意一些资源同步。