import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.Scanner;
//这是一个用udp接收广播的程序
public class UDPclien {
int port=6666;
boolean b=false;
Thread thread=null;
//以下是建立7788的,本来这里调用了循环,我放到run方法里面去了
private void Receiver(InetAddress group) throws Exception {
byte data[]=new byte[1024];
DatagramPacket packet=new DatagramPacket(data, data.length,group,port);
MulticastSocket socket=new MulticastSocket(port);
socket.joinGroup(group);
socket.receive(packet);
String s=new String(packet.getData());
System.out.println(s);
}
//把runnable对象独立出来了,这里调用了循环
private Runnable getRun() {
Runnable runnable=new Runnable() {
public void run() {
try {
InetAddress group=InetAddress.getByName("224.255.10.0");
while(true) {
Receiver(group);
if(b==true) {
break;
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
return runnable;
}
//这里建立收听广播的线程
private void action(int a) {
if(a==1) {
if(thread==null) {
thread=new Thread(getRun());thread.start();
}
else if(!(thread.isAlive())){
thread=new Thread(getRun());thread.start();
}
else {
b=false;
thread.run();//尝试过在这里加上循环,也没用
}
}
else if(a==0) {
b=true;
}
else {}
}
private void seta(int a) {
action(a);
}
public static void main(String[] args) {
UDPclien clien=new UDPclien();
Scanner in=new Scanner(System.in);
Thread thread=new Thread(new Runnable() {
public void run() {
while(true) {
int a=in.nextInt();
if(a==2) {
break;
}
clien.seta(a);
}
}
});
thread.start();
}
}我另外写了一个代码不断的发送广播,没有问题。这个代码,输入1可以一直接收广播,输入0会结束,但是再次输入1就只会执行一次。感觉不应该啊,我嵌套的好几次while死循环都不能实现再次启动,求大神指点
1 回答
添加回答
举报
0/150
提交
取消