Socket通道可以通过调用其静态 open()方法来创建,然后调用 connect()方法进行链接,如果连接失败,则引发NotYetConnectedException异常。可以通过调用其 isConnected 方法来判断是否已连接。
Socket通道可以通过 finishConnect()方法来完成。可以通过调用isConnectionPending方法来确定是否正在进行连接操作。
bind(SocketAddress local) - 此方法用于将Socket通道绑定本地地址。
connect(SocketAddress remote) - 此方法用于将Socket连接到远程地址。
finishConnect() - 此方法用于完成Socket通道的连接过程。
getRemoteAddress() - 此方法返回通道Socket连接到的远程位置的地址。
isConnected() - 此方法返回Socket通道的连接状态,即是否已连接。
open()和open(SocketAddress remote) - 使用open方法打开Socket通道。
read(ByteBuffer dst) - 此方法用于通过Socket通道从给指定的缓冲区中读取数据。
isConnectionPending() - 此方法用于判断此通道上是否正在进行连接操作。
以下示例显示了如何从Java NIO SocketChannel发送数据。
C:/Test/temp.txt
Hello World!
SocketChannelClient.java
import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.EnumSet; public class SocketChannelClient { public static void main(String[] args) throws IOException { ServerSocketChannel serverSocket = null; SocketChannel client = null; serverSocket = ServerSocketChannel.open(); serverSocket.socket().bind(new InetSocketAddress(9000)); client = serverSocket.accept(); System.out.println("Connection Set: " + client.getRemoteAddress()); Path path = Paths.get("C:/Test/temp1.txt"); FileChannel fileChannel = FileChannel.open(path, EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE) ); ByteBuffer buffer = ByteBuffer.allocate(1024); while(client.read(buffer) > 0) { buffer.flip(); fileChannel.write(buffer); buffer.clear(); } fileChannel.close(); System.out.println("File Received"); client.close(); } }
在服务器启动之前,运行客户端将不会打印任何内容。
SocketChannelServer.java
import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.SocketChannel; import java.nio.file.Path; import java.nio.file.Paths; public class SocketChannelServer { public static void main(String[] args) throws IOException { SocketChannel server = SocketChannel.open(); SocketAddress socketAddr = new InetSocketAddress("localhost", 9000); server.connect(socketAddr); Path path = Paths.get("C:/Test/temp.txt"); FileChannel fileChannel = FileChannel.open(path); ByteBuffer buffer = ByteBuffer.allocate(1024); while(fileChannel.read(buffer) > 0) { buffer.flip(); server.write(buffer); buffer.clear(); } fileChannel.close(); System.out.println("File Sent"); server.close(); } }
运行服务器将打印以下内容。
Connection Set: /127.0.0.1:49558 File Received
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)