您的位置:首页 > 编程语言 > Java开发

Java Nio UDP 消息发送

2014-02-26 11:21 288 查看
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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java nio udp