基于Java NIO 的socket通信实例
2016-01-22 22:12
459 查看
服务端代码
客户端代码
package com.lp.socket; 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 NioServerSocket { public static void main(String[] args) { HandlerSelectionKey handler = new HandlerHandlerSelectionKeyImpl(); try { //创建 ServerSocketChannel ServerSocketChannel server = ServerSocketChannel.open(); server.configureBlocking(false); server.bind(new InetSocketAddress("localhost", 12345)); //创建 Selector Selector selector = Selector.open(); server.register(selector, SelectionKey.OP_ACCEPT); //死循环,持续接收 客户端连接 while(true) { //selector.select(); 是阻塞方法 int keys = selector.select(); if(keys > 0) { Iterator<SelectionKey> it = selector.selectedKeys().iterator(); while(it.hasNext()) { SelectionKey key = it.next(); it.remove(); //处理 SelectionKey handler.handler(key, selector); } } } } catch (IOException e) { e.printStackTrace(); } } /** * SelectionKey 处理接口 * */ public static interface HandlerSelectionKey { public void handler(SelectionKey key, Selector selector) throws IOException; } /** * SelectionKey 接口 实现类 * */ public static class HandlerHandlerSelectionKeyImpl implements HandlerSelectionKey { @Override public void handler(SelectionKey key, Selector selector) throws IOException { int keyState = selectionKeyState(key); switch (keyState) { case SelectionKey.OP_ACCEPT: ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel(); accept(serverSocketChannel, selector); break; case SelectionKey.OP_READ: SocketChannel readSocketChannel = (SocketChannel) key.channel(); read(readSocketChannel, selector); break; case SelectionKey.OP_WRITE: SocketChannel writeSocketChannel = (SocketChannel) key.channel(); write(writeSocketChannel, selector); break; } } /** * 获取 SelectionKey 是什么事件 * @param key * @return */ private int selectionKeyState(SelectionKey key) { if(key.isAcceptable()) { return SelectionKey.OP_ACCEPT; } else if(key.isReadable()) { return SelectionKey.OP_READ; } else if(key.isWritable()) { return SelectionKey.OP_WRITE; } return -1; } /** * 接口客户端请求 * @param serverSocketChannel * @param selector * @throws IOException */ private void accept(ServerSocketChannel serverSocketChannel, Selector selector) throws IOException { SocketChannel socketChannel = serverSocketChannel.accept(); socketChannel.configureBlocking(false); //将 channel 注册到 Selector socketChannel.register(selector, SelectionKey.OP_READ); } /** * 读取客户端发送过来的信息 * @param socketChannel * @param selector * @throws IOException */ private void read(SocketChannel socketChannel, Selector selector) throws IOException { ByteBuffer readBuffer = ByteBuffer.allocate(8192); int readBytes = socketChannel.read(readBuffer); if(readBytes > 0) { System.out.println("客户端发送来的消息"); System.out.println(new String(readBuffer.array(), 0, readBytes)); } //将 channel 注册到 Selector socketChannel.register(selector, SelectionKey.OP_WRITE); } /** * 响应客户端请求 * @param socketChannel * @param selector * @throws IOException */ private void write(SocketChannel socketChannel, Selector selector) throws IOException { //响应消息 String responseMsg = "hello client, i am server"; byte[] responseByte = responseMsg.getBytes(); ByteBuffer writeBuffer = ByteBuffer.allocate(responseByte.length); writeBuffer.put(responseByte); writeBuffer.flip(); //响应客户端 socketChannel.write(writeBuffer); socketChannel.finishConnect(); socketChannel.close(); } } }
客户端代码
package com.lp.socket; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; public class NioClientSocket { public static void main(String[] args) throws IOException { //打开 SocketChannel SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("localhost", 12345)); //设置为 非阻塞 socketChannel.configureBlocking(false); //给服务端发送信息 socketChannel.write(ByteBuffer.wrap("Actions speak louder than words!".getBytes())); ByteBuffer readBuffer = ByteBuffer.allocate(512); while (true) { readBuffer.clear(); int readBytes = socketChannel.read(readBuffer); if (readBytes > 0) { readBuffer.flip(); System.out.println("Client: readBytes = " + readBytes); System.out.println("Client: data = " + new String(readBuffer.array(), 0, readBytes)); socketChannel.close(); break; } } } }
相关文章推荐
- Spring Boot 多数据源
- JavaSE010_数组之二维数组的实质和遍历
- Java中接口的说明
- eclipse黑色酷炫主题设置2
- MyEclipse弹出提示窗体
- dom4j java.lang.NoClassDefFoundError: org/jaxen/JaxenException
- 【SSH】——struts2 拦截器
- 为Java说句公道话
- Java 创建不可变对象-final关键字的使用总结
- 使用Maven管理Spring
- Java和C + +有什么区别?
- SpringMVC,MyBatis商品的增删改查
- Maven(m2e)集成之二
- JavaSE009_数组之foreach循环
- [Java基础] 深入jar包:从jar包中读取资源文件
- hdfs java.io.IOException: Mkdirs failed to create
- hadoop - hadoop2.6 伪分布式 - Java API 操作 HDFS
- java点滴之InetAddress类和InetSocketAddress的使用
- 【Java】【编译】javac编译源代码时,若源文件使用了别的java源代码的函数,javac会自动关联。
- Java多线程2