关于Java的MulticastSocket 同时Receive与Send相互不阻塞
直接上代码:
package org.eyet.net.udp.multicast.test;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import org.junit.Test;
public class MulticastTest {
private MulticastSocket multicastSocket;
private InetAddress group;
public static void main(String[] args) throws IOException{
new MulticastTest().testSingleMulticastRecvAndSend();
}
@Test
public void testSingleMulticastRecvAndSend() throws IOException {
group = InetAddress.getByName("228.5.6.7");
multicastSocket = new MulticastSocket(6789);
multicastSocket.joinGroup(group);// 加入该组
new Thread(new Runnable() {
public void run() {
byte[] arb = new byte[1024];
System.out.println("run receive");
while (true) {
DatagramPacket datagramPacket = new DatagramPacket(arb,
arb.length);
try {
multicastSocket.receive(datagramPacket);
Thread.sleep(1000);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(arb.length);
System.out.println(new String(arb));
}
}
}).start();
new Thread(new Runnable() {
public void run() {
int i=0;
try {
Thread.sleep(1100);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("run send");
while(true && i<10){
String sendMessage = "hello world"+i++;
DatagramPacket datagramPacket = new DatagramPacket(
sendMessage.getBytes(), sendMessage.length(), group,
6789);
try {
multicastSocket.send(datagramPacket);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("send over");
}
}).start();
}
}
输出结果:
run receive
run send
send over
1024
hello world0
……
可以看到receive先运行,但还能使用send方法进行发送
所以我判断receive与send能同时运行
请各位多多指教。