关于Java的MulticastSocket 同时Receive与Send相互不阻塞

关于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能同时运行

 

请各位多多指教。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值