Java Nio UDP 消息发送

本文详细探讨了如何使用Java NIO进行UDP通信,涵盖了创建DatagramSocket、编写Buffer、发送与接收数据包的步骤,以及在实际应用中可能遇到的问题和解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package ch3;

import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.charset.Charset;
import java.util.Iterator;

/**
 * UDP 传送数据服务器
 * @author Administrator
 *
 */
public class UDPServerSocket {

	public static void main(String[] args) throws Exception {
		//打开UDP数据包通道
		DatagramChannel dgc=DatagramChannel.open();
		//设置非阻塞模式
		dgc.configureBlocking(false);
		//打开选择器
		Selector selector = Selector.open();
		//绑定服务器端口
		dgc.socket().bind(new InetSocketAddress(10001));
		//注册选择器
		dgc.register(selector, SelectionKey.OP_READ);
		System.out.println("UDP 服务器开启");
		ByteBuffer bb=ByteBuffer.allocateDirect(8);
		while(true){
			selector.select();
			Iterator<SelectionKey> keys=selector.selectedKeys().iterator();
			while(keys.hasNext()){
				SelectionKey sk=keys.next();
				//判断是否准备好进行读取
				if(sk.isReadable()){
					DatagramChannel curdc=(DatagramChannel) sk.channel();
					//接收数据
					InetSocketAddress address=(InetSocketAddress) curdc.receive(bb);
					System.out.println("接收来自:"+address.getAddress().getHostAddress()+":"+address.getPort());
					bb.flip();
					byte[] b= new byte[bb.limit()];
					for(int i=0;i<bb.limit();i++){
						b[i]=bb.get(i);
					}
					System.out.println(new String(b));
					bb.clear();
					//返回消息给发送端
					ByteBuffer cbc = ByteBuffer.allocate(8);
					cbc.put("byte".getBytes());
					cbc.flip();
					curdc.send(cbc, address);
				}
			}
		}
	}
}



package ch3;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.charset.Charset;
import java.util.Iterator;
/**
 * UDP消息发送客户端
 * @author Administrator
 *
 */
public class UDPClientSocket {

	public static void main(String[] args) throws Exception {
		DatagramChannel dgc= DatagramChannel.open();
		dgc.configureBlocking(false);
		InetSocketAddress isa = new InetSocketAddress("localhost",10001);
		//连接
		dgc.connect(isa);
		ByteBuffer bb=ByteBuffer.allocate(8);
		bb.put("哈哈".getBytes("UTF-8"));
		bb.flip();
		dgc.send(bb,isa);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值