12. Java NIO DatagramChannel 数据报通道
2019獨角獸企業(yè)重金招聘Python工程師標準>>>
一個Java NIO DatagramChannel死一個可以發(fā)送、接收UDP數(shù)據(jù)包的通道。由于UDP是面向無連接的網(wǎng)絡協(xié)議,我們不可用像使用其他通道一樣直接進行讀寫數(shù)據(jù)。正確的做法是發(fā)送、接收數(shù)據(jù)包。
打開一個DatagramChannel(Opening a DatagramChannel)
打開一個DatagramChannel你這么操作:
DatagramChannel channel = DatagramChannel.open(); channel.socket().bind(new InetSocketAddress(9999));上述示例中,我們打開了一個DatagramChannel,它可以在9999端口上收發(fā)UDP數(shù)據(jù)包。
接收數(shù)據(jù)(Receiving Data)
接收數(shù)據(jù),直接調(diào)用DatagramChannel的receive()方法:
ByteBuffer buf = ByteBuffer.allocate(48); buf.clear();**channel.receive(buf);**receive()方法會把接收到的數(shù)據(jù)包中的數(shù)據(jù)拷貝至給定的Buffer中。如果數(shù)據(jù)包的內(nèi)容超過了Buffer的大小,剩余的數(shù)據(jù)會被直接丟棄。
發(fā)送數(shù)據(jù)(Sending Data)
發(fā)送數(shù)據(jù)是通過DatagramChannel的send()方法:
String newData = "New String to wrte to file..." +System.currentTimeMillis(); ByteBuffer buf = ByteBuffer.allocate(48); buf.clear(); buf.put(newData.getBytes()); buf.flip();**int byteSent = channel.send(buf, new InetSocketAddress("jenkov.com", 80));**上述示例會吧一個字符串發(fā)送到“jenkov.com”服務器的UDP端口80.目前這個端口沒有被任何程序監(jiān)聽,所以什么都不會發(fā)生。當發(fā)送了數(shù)據(jù)后,我們不會收到數(shù)據(jù)包是否被接收的的通知,這是由于UDP本身不保證任何數(shù)據(jù)的發(fā)送問題。
鏈接特定機器地址(Connecting to a Specific Address)
DatagramChannel實際上是可以指定到網(wǎng)絡中的特定地址的。由于UDP是面向無連接的,這種鏈接方式并不會創(chuàng)建實際的連接,這和TCP通道類似。確切的說,他會鎖定DatagramChannel,這樣我們就只能通過特定的地址來收發(fā)數(shù)據(jù)包。
看一個例子先:
channel.connect(new InetSocketAddress("jenkov.com"), 80));當連接上后,可以向使用傳統(tǒng)的通道那樣調(diào)用read()和Writer()方法。區(qū)別是數(shù)據(jù)的讀寫情況得不到保證。下面是幾個示例:
int bytesRead = channel.read(buf); int bytesWritten = channel.write(buf);轉(zhuǎn)載于:https://my.oschina.net/gaoguofan/blog/790812
總結
以上是生活随笔為你收集整理的12. Java NIO DatagramChannel 数据报通道的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 枚举类的定义和使用
- 下一篇: I00040 计算1000以内的勾股数