关于IP组播客户端运行总是卡死的问题,各位大神帮帮忙!急!

jxls080511 2012-04-08 05:45:00
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)上面,不知如何修改
...全文
105 点赞 收藏 3
写回复
3 条回复
切换为时间正序
当前发帖距今超过3年,不再开放新的回复
发表回复
fangzhen2005 2012-04-09
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();

差不多这样,注意一些资源同步。
回复
jxls080511 2012-04-08
创建线程?可不可以给点简单的代码,请指教!谢谢了
回复
fangzhen2005 2012-04-08
mulSocket.receive(packet); 方法是阻塞的,可以创建一个线程,专门用于接收处理数据
回复
相关推荐
发帖
Java SE
创建于2007-09-28

6.1w+

社区成员

Java 2 Standard Edition
申请成为版主
帖子事件
创建了帖子
2012-04-08 05:45
社区公告
暂无公告