Java的NIO包中,有一個專門用于發送UDP數據包的類:DatagramChannel,UDP是一種無連接的網絡協議,
一般用于發送一些準確度要求不太高的數據等。
完整的服務端程序如下:
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 { //每次發送接收的數據包大小 private final int MAX_BUFF_SIZE = 1024 * 10 ; //服務端監聽端口,客戶端也通過該端口發送數據 private int port; private DatagramChannel channel; private Selector selector; private ScheduledExecutorService es = Executors.newScheduledThreadPool( 1 ); public void init() throws IOException { //創建通道和選擇器 selector = Selector.open(); channel = DatagramChannel.open(); //設置為非阻塞模式 channel.configureBlocking( false ); channel.socket().bind( new InetSocketAddress(port)); //將通道注冊至selector,監聽只讀消息(此時服務端只能讀數據,無法寫數據) channel.register(selector, SelectionKey.OP_READ); //使用線程的方式,保證服務端持續等待接收客戶端數據 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()) { //接收數據 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); } //處理接收到的數據 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); } } } |
客戶端發送完整例子如下:
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為服務端IP地址,端口和服務端的端口一致 int n = channel.send(buffer, new InetSocketAddress( "127.0.0.1" , 8080 )); System.out.println(n); //每次數據發送完畢之后,一定要調用close方法,來關閉占用的udp端口,否則程序不結束,端口不會釋放 channel.close(); |
總結
以上就是本文關于Java NIO實例UDP發送接收數據代碼分享的全部內容,希望對大家有所幫助。有什么問題可以隨時留言,小編會及時回復大家的。感謝朋友們對本站的支持!
原文鏈接:http://blog.csdn.net/lzy_lizhiyang/article/details/61914581