Java Nio UDP 消息发送

来源:互联网 发布:天敏网络机顶盒无信号 编辑:程序博客网 时间:2024/05/01 19:15
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);}}


0 0