Java——SocketChannel
程序员文章站
2022-04-03 09:19:27
...
SocketChannel是NIO形式的客户端服务器通信的形式,支持异步非阻塞连接,通过管道与缓存的形式进行通信,与Java的Socket是有区别的,socket是通过请求——连接的形式进行通信,而SocketChannel是通过建立管道的形式进行通信,原则上,SocketChannel要比Socket快,这只是自己的理解,不知道正确与否了。。。下面总结下SocketChannel形式的代码实现:
一、服务器端:
import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; public class ServerSocketChannelTest { public static void main(String[] args) throws Exception { ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.socket().bind(new InetSocketAddress(9999)); while(true){ SocketChannel socketChannel = serverSocketChannel.accept(); ByteBuffer buf = ByteBuffer.allocate(48); int bytesRead = socketChannel.read(buf); while (bytesRead != -1) { System.out.println("Read " + bytesRead); buf.flip(); while(buf.hasRemaining()){ System.out.print((char) buf.get()); } buf.clear(); bytesRead = socketChannel.read(buf); } } } }
这个阻塞的形式,也就是在serverSocketChannel.accept();处,只有当客户端有请求进行通道链接时,才会向下执行,下面是非阻塞形式的代码:
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.socket().bind(new InetSocketAddress(9999)); serverSocketChannel.configureBlocking(false); //设置为非阻塞式 while(true){ SocketChannel socketChannel = serverSocketChannel.accept(); if(socketChannel != null){ //为非阻塞式时,要进行非空判断 //do something with socketChannel... } }
二、客户端代码:
import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; public class SocketChannelTest { public static void main(String[] args) throws Exception { SocketChannel socketChannel = SocketChannel.open(); socketChannel.connect(new InetSocketAddress("localhost", 9999)); String newData = "New String to write to socket...." + System.currentTimeMillis(); ByteBuffer buf = ByteBuffer.allocate(48); buf.clear(); buf.put(newData.getBytes()); buf.flip(); while(buf.hasRemaining()) { socketChannel.write(buf); } socketChannel.close(); } }
上一篇: 如何解决php gzip 乱码问题
下一篇: Java中需要编码的场景