Java的NIO包中,有一個專門用于發(fā)送UDP數(shù)據(jù)包的類:DatagramChannel,UDP是一種無連接的網(wǎng)絡(luò)協(xié)議,
一般用于發(fā)送一些準(zhǔn)確度要求不太高的數(shù)據(jù)等。

完整的服務(wù)端程序如下:
public class StatisticsServer {
//每次發(fā)送接收的數(shù)據(jù)包大小
private final int MAX_BUFF_SIZE = 1024 * 10;
//服務(wù)端監(jiān)聽端口,客戶端也通過該端口發(fā)送數(shù)據(jù)
private int port;
private DatagramChannel channel;
private Selector selector;
private ScheduledExecutorService es = Executors.newScheduledThreadPool(1);
public void init() throws IOException {
//創(chuàng)建通道和選擇器
selector = Selector.open();
channel = DatagramChannel.open();
//設(shè)置為非阻塞模式
channel.configureBlocking(false);
channel.socket().bind(new InetSocketAddress(port));
//將通道注冊至selector,監(jiān)聽只讀消息(此時服務(wù)端只能讀數(shù)據(jù),無法寫數(shù)據(jù))
channel.register(selector, SelectionKey.OP_READ);
//使用線程的方式,保證服務(wù)端持續(xù)等待接收客戶端數(shù)據(jù)
es.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
try {
while(selector.select() > 0) {
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while(iterator.hasNext()) {
SelectionKey key = iterator.next();
try {
iterator.remove();
if(key.isReadable()) {
//接收數(shù)據(jù)
doReceive(key);
}
} catch (Exception e) {
logger.error("SelectionKey receive exception", e);
try {
if (key != null) {
key.cancel();
key.channel().close();
}
} catch (ClosedChannelException cex) {
logger.error("Close channel exception", cex);
}
}
}
}
} catch (IOException e) {
logger.error("selector.select exception", e);
}
}
}, 0L, 2L, TimeUnit.MINUTES);
}
//處理接收到的數(shù)據(jù)
private void doReceive(SelectionKey key) throws IOException {
String content = "";
DatagramChannel sc = (DatagramChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(MAX_BUFF_SIZE);
buffer.clear();
sc.receive(buffer);
buffer.flip();
while(buffer.hasRemaining()) {
byte[] buf = new byte[buffer.limit()];
buffer.get(buf);
content += new String(buf);
}
buffer.clear();
logger.debug("receive content="+content);
if(StringUtils.isNotBlank(content)) {
doSave(content);
}
}
}
網(wǎng)站標(biāo)題:JavaNIO實例UDP發(fā)送接收數(shù)據(jù)代碼分享-創(chuàng)新互聯(lián)
文章轉(zhuǎn)載:http://chinadenli.net/article48/cdcdep.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設(shè)計、用戶體驗、網(wǎng)站內(nèi)鏈、移動網(wǎng)站建設(shè)、網(wǎng)站排名、App設(shè)計
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)