TCP 使用NIO

关于java 的TCP消息处理,系统给我们提供的有Socket InputStream,OutputStream 简单的小系统使用可以满足要求。假如你的系统与如下需求呢,客户端需要同时跟五个服务器建立连接,并且处理五个服务器的数据,你会怎么处理,一个线程处理一个服务器的数据吗?那么至少需要五个线程,对于系统来说消耗的资源太多,并且多个线程如果访问同一种数据会出现数据同步的问题,那么有没有考虑过使用一个线程来处理五个服务器的数据,那么有一个首要的问题就是就是不能读取数据的时候不能线程阻塞。NIO的强大功能来自channel的非阻塞特性。我们知道InputStream的read()方法,会一直阻塞,知道有数据的来临,如果使用inputStream来读取服务器的数据,显然是不合理的。

NIO的channel的一个重要特征就是通过配置它的阻塞行为,实现非阻塞通道 channel.configureBlocking(false).在非阻塞信道上,调用一个方法总是会立即返回,例如在一个非阻塞的信道上ServerSocketChannel.accept()方法,如果有客户端在等待,则返回socketchannel,如果么有则返回null.

可能阻塞的I/0操作包括建立连接,读数据,写数据,通过非阻塞信道,这些操作都立即返回,我们必须反复调用这些操作,直到I/O完成。

转载于:https://www.cnblogs.com/wjsd/p/5501169.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个使用Java NIO实现的TCP Server和Client的示例代码: TCP Server: ```java import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; public class TCPServer { private Selector selector; private ByteBuffer buffer = ByteBuffer.allocate(1024); public TCPServer(int port) throws IOException { ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.configureBlocking(false); serverSocketChannel.socket().bind(new InetSocketAddress(port)); selector = Selector.open(); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); System.out.println("Server started on port " + port); } private void start() throws IOException { while (true) { selector.select(); Iterator<SelectionKey> keys = selector.selectedKeys().iterator(); while (keys.hasNext()) { SelectionKey key = keys.next(); keys.remove(); if (!key.isValid()) { continue; } if (key.isAcceptable()) { accept(key); } else if (key.isReadable()) { read(key); } else if (key.isWritable()) { write(key); } } } } private void accept(SelectionKey key) throws IOException { ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel(); SocketChannel socketChannel = serverSocketChannel.accept(); socketChannel.configureBlocking(false); socketChannel.register(selector, SelectionKey.OP_READ); System.out.println("Accepted connection from " + socketChannel.getRemoteAddress()); } private void read(SelectionKey key) throws IOException { SocketChannel socketChannel = (SocketChannel) key.channel(); buffer.clear(); int bytesRead = socketChannel.read(buffer); if (bytesRead == -1) { socketChannel.close(); System.out.println("Connection closed by " + socketChannel.getRemoteAddress()); return; } buffer.flip(); byte[] data = new byte[buffer.limit()]; buffer.get(data); System.out.println("Received data from " + socketChannel.getRemoteAddress() + ": " + new String(data)); socketChannel.register(selector, SelectionKey.OP_WRITE, data); } private void write(SelectionKey key) throws IOException { SocketChannel socketChannel = (SocketChannel) key.channel(); byte[] data = (byte[]) key.attachment(); ByteBuffer byteBuffer = ByteBuffer.wrap(data); socketChannel.write(byteBuffer); System.out.println("Sent data to " + socketChannel.getRemoteAddress() + ": " + new String(data)); socketChannel.register(selector, SelectionKey.OP_READ); } public static void main(String[] args) throws IOException { TCPServer server = new TCPServer(8080); server.start(); } } ``` TCP Client: ```java import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; public class TCPClient { private SocketChannel socketChannel; private ByteBuffer buffer = ByteBuffer.allocate(1024); public TCPClient(String host, int port) throws IOException { socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); socketChannel.connect(new InetSocketAddress(host, port)); } private void start() throws IOException { while (!socketChannel.finishConnect()) { // Wait for connection to be established } System.out.println("Connected to server " + socketChannel.getRemoteAddress()); String message = "Hello, server!"; buffer.put(message.getBytes()); buffer.flip(); socketChannel.write(buffer); System.out.println("Sent data to server: " + message); buffer.clear(); int bytesRead = socketChannel.read(buffer); if (bytesRead == -1) { socketChannel.close(); System.out.println("Connection closed by server"); return; } buffer.flip(); byte[] data = new byte[buffer.limit()]; buffer.get(data); System.out.println("Received data from server: " + new String(data)); socketChannel.close(); } public static void main(String[] args) throws IOException { TCPClient client = new TCPClient("localhost", 8080); client.start(); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值