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);
}
}
相关文章推荐
- rsyslog用tcp/udp发送日志消息最大2k的限制配置
- (unix domain socket)使用udp发送>=128K的消息会报ENOBUFS的错误
- 使用udp协议给飞Q发送消息
- Qt开发:UDP、TCP发送文字消息、检测U盘插拔、SYSZUXpinyin软键盘输入法移植------[源码奉送]
- UDP通信类,监听本机指定端口,发送消息给指定电脑
- Linux系统下UDP发送和接收广播消息小例子
- qt 下UDP消息的接收和发送和TCP发送文件
- python,UPD,socket(一) 使用udp 发送消息
- udp发送和接收消息,服务端
- 示例C#利用UdpClient发送广播消息<转>
- QUdpSocket简单使用Demo(局域网内发送给所有客户端消息与接收)
- (unix domain socket)使用udp发送>=128K的消息会报ENOBUFS的错误
- UDP通信类,监听本机指定端口,发送消息给指定电脑
- tcp文件传输(udp发送消息确定是否接收)
- Udp消息发送接收示例
- (unix domain socket)使用udp发送>=128K的消息会报ENOBUFS的错误
- UDP实现内网到网的点对点发送消息与转发消息
- (unix domain socket)使用udp发送>=128K的消息会报ENOBUFS的错误
- Linux系统下UDP发送和接收广播消息小例子
- UDP发送组播消息