Java NIO数据报用作通道,可以通过较少连接的协议发送和接收UDP数据包。默认情况下,数据报通道处于阻塞状态,也可以在非阻塞模式下使用。为了使其成为非阻塞状态,无涯教程可以使用configureBlocking( false)方法。可以通过调用名为 open()的静态方法之一来打开DataGram通道,该方法也可以使用IP地址作为参数,以便将其用于多类型转换。
默认情况下,不连接FileChannel的数据报通道以使其连接,必须显式调用其connect()方法,但是不必连接数据报通道以在必须连接时使用send和receive方法为了使用读写方法。
可以通过调用其 isConnected()方法来检查数据报通道的连接状态。
bind(SocketAddress local) - 此方法用于将数据报绑定到本地地址。
connect(SocketAddress remote) - 此方法用于将Socket连接到远程地址。
disconnect() - 此方法用于将Socket断开与远程地址的连接。
getRemoteAddress() - 此方法返回通道Socket连接到的远程位置的地址。
isConnected() - 该方法返回数据报通道的连接状态,即是否已连接。
open()和open(ProtocolFamily family) - Open方法用于为单个地址打开一个数据报通道,而参数open方法为多个地址的打开通道。
read(ByteBuffer dst) - 此方法用于通过数据报通道从给定的缓冲区读取数据。
receive(ByteBuffer dst) - 此方法用于通过此通道接收数据报。
send(ByteBuffer src,SocketAddress target) - 此方法用于通过此通道发送数据报。
以下示例显示了如何从Java NIO DataGramChannel发送数据。
DatagramChannelServer.java
import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; public class DatagramChannelServer { public static void main(String[] args) throws IOException { DatagramChannel server = DatagramChannel.open(); InetSocketAddress iAdd = new InetSocketAddress("localhost", 8989); server.bind(iAdd); System.out.println("Server Started: " + iAdd); ByteBuffer buffer = ByteBuffer.allocate(1024); //从客户端接收缓冲区。 SocketAddress remoteAdd = server.receive(buffer); //改变缓冲区模式 buffer.flip(); int limits = buffer.limit(); byte bytes[] = new byte[limits]; buffer.get(bytes, 0, limits); String msg = new String(bytes); System.out.println("Client at " + remoteAdd + " sent: " + msg); server.send(buffer,remoteAdd); server.close(); } }
运行上面代码输出
Server Started: localhost/127.0.0.1:8989
DatagramChannelClient.java
import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; public class DatagramChannelClient { public static void main(String[] args) throws IOException { DatagramChannel client = null; client = DatagramChannel.open(); client.bind(null); String msg = "Hello World!"; ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes()); InetSocketAddress serverAddress = new InetSocketAddress("localhost", 8989); client.send(buffer, serverAddress); buffer.clear(); client.receive(buffer); buffer.flip(); client.close(); } }
运行客户端将在服务器上打印以下输出。
Server Started: localhost/127.0.0.1:8989 Client at /127.0.0.1:64857 sent: Hello World!
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)