Java的NIO包中,有一個專門用于發(fā)送UDP數(shù)據(jù)包的類:DatagramChannel,UDP是一種無連接的網絡協(xié)議,
一般用于發(fā)送一些準確度要求不太高的數(shù)據(jù)等。
完整的服務端程序如下:
public class StatisticsServer { //每次發(fā)送接收的數(shù)據(jù)包大小 private final int MAX_BUFF_SIZE = 1024 * 10; //服務端監(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(); //設置為非阻塞模式 channel.configureBlocking(false); channel.socket().bind(new InetSocketAddress(port)); //將通道注冊至selector,監(jiān)聽只讀消息(此時服務端只能讀數(shù)據(jù),無法寫數(shù)據(jù)) channel.register(selector, SelectionKey.OP_READ); //使用線程的方式,保證服務端持續(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); } } }
網站標題:JavaNIO實例UDP發(fā)送接收數(shù)據(jù)代碼分享-創(chuàng)新互聯(lián)
文章轉載:http://muchs.cn/article48/cdcdep.html
成都網站建設公司_創(chuàng)新互聯(lián),為您提供網站設計、用戶體驗、網站內鏈、移動網站建設、網站排名、App設計
聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)