DatagramChannel使用
来源:互联网 发布:关于淘宝客服常用语 编辑:程序博客网 时间:2024/04/28 17:21
DatagramChannel是nio中处理UDP的类,可以使用2种方式:
DatagramChannel.receive(ByteBuffer dst)和DatagramChannel.send(ByteBuffer src, SocketAddress target)
调用connect()之后,使用read和write.
方式一
send和receive示例
/** * @author cxg * */public class DatagramChannelSender {public static void main(String[] args) {try {send();} catch (IOException e) {e.printStackTrace();}}private static void send() throws IOException{DatagramChannel channel =DatagramChannel.open();ByteBuffer buffer =ByteBuffer.wrap("下雨的夜晚很安静".getBytes("utf-8"));channel.send(buffer, new InetSocketAddress("localhost",10022));channel.close();}}
/** * @author cxg * */public class DatagramChannelReveiver {public static void main(String[] args) {try {receive();} catch (IOException e) {e.printStackTrace();}}private static void receive() throws IOException{DatagramChannel channel =DatagramChannel.open();channel.socket().bind(new InetSocketAddress(10022));ByteBuffer buffer =ByteBuffer.allocate(60);while(channel.receive(buffer)==null){ try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}buffer.flip();String recStr =Charset.forName("utf-8").newDecoder().decode(buffer).toString();System.out.println(recStr);channel.close();}}
方式2
connect()说明
1.只起到,限制数据包的接收和发送来源
2.不会阻塞
3.使用read和write的必要条件,否则抛出"NotYetConnectedException "
其他注意
DatagramChannel不能注册SelectionKey.OP_CONNECT
数据包的最大容量是65507字节
0 0
- DatagramChannel使用
- Java-DatagramChannel使用
- DatagramChannel异常
- DatagramChannel.send
- DatagramChannel.send和DatagramChannel.write
- Java NIO DatagramChannel
- DatagramChannel的用法
- Java NIO(11-DatagramChannel)
- Java NIO DatagramChannel
- java nio(四):DatagramChannel
- Java NIO (十) DatagramChannel
- Java NIO DatagramChannel
- Java NIO DatagramChannel
- Java NIO DatagramChannel
- 九、Nio之DatagramChannel
- Java NIO DatagramChannel UDP
- NIO 03 DatagramChannel
- NIO学习(七) DataGramChannel
- hdu 2686 Matrix(最大费用流)
- centos 安装gcc4.8
- 点击按钮弹出新窗口,输入数据后返回并刷新页面(C#代码) 窗口互传值
- 2013,2014
- struts的action访问servlet的IOC方式与非IOC方式
- DatagramChannel使用
- Oracle笔记(六) 多表查询
- telnet 失去了跟主机的连接
- MySQL学习笔记 7 -数据备份与还原
- linux块设备加速缓存之bcache
- c#委托
- 13总结
- 集群环境中使用 EhCache 缓存系统
- python版文件批量改名