Java的NIO包中,有一個專門用于發(fā)送UDP數(shù)據(jù)包的類:DatagramChannel,UDP是一種無連接的網(wǎng)絡(luò)協(xié)議,
一般用于發(fā)送一些準(zhǔn)確度要求不太高的數(shù)據(jù)等。
完整的服務(wù)端程序如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
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); } } } |
客戶端發(fā)送完整例子如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
DatagramChannel channel = DatagramChannel.open(); StringBuilder sb = new StringBuilder(); sb.append( "2017-03-09 12:30:00;" ) .append( "aaa" ) .append( "testapp;" ) .append( "test.do;" ) .append( "param=hello;" ) .append( "test;" ) .append( "100;" ) .append( "1" ); ByteBuffer buffer = ByteBuffer.allocate( 10240 ); buffer.clear(); buffer.put(sb.toString().getBytes()); buffer.flip(); //此處IP為服務(wù)端IP地址,端口和服務(wù)端的端口一致 int n = channel.send(buffer, new InetSocketAddress( "127.0.0.1" , 8080 )); System.out.println(n); //每次數(shù)據(jù)發(fā)送完畢之后,一定要調(diào)用close方法,來關(guān)閉占用的udp端口,否則程序不結(jié)束,端口不會釋放 channel.close(); |
總結(jié)
以上就是本文關(guān)于Java NIO實例UDP發(fā)送接收數(shù)據(jù)代碼分享的全部內(nèi)容,希望對大家有所幫助。有什么問題可以隨時留言,小編會及時回復(fù)大家的。感謝朋友們對本站的支持!
原文鏈接:http://blog.csdn.net/lzy_lizhiyang/article/details/61914581