Java异步套接字实例
2024-10-21 18:50:27
服务端
package com.test.server; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; 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.Set; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.*; import java.nio.*; import java.nio.channels.*; class AsynServer { static private int BUFFER_SIZE = 256; //定义一个临时的socket SocketChannel sc; public void start() { try { //定义一个事件选择器对象记录套接字通道的事件 Selector selector = Selector.open(); //定义一个异步服务器socket对象 ServerSocketChannel ssc = ServerSocketChannel.open(); //将此socket对象设置为异步 ssc.configureBlocking(false); //定义服务器socket对象-用来指定异步socket的监听端口等信息 ServerSocket ss = ssc.socket(); //定义存放监听端口的对象 InetSocketAddress address = new InetSocketAddress(55555); //将服务器与这个端口绑定 ss.bind(address); //将异步的服务器socket对象的接受客户端连接事件注册到selector对象内 ssc.register(selector, SelectionKey.OP_ACCEPT); System.out.println("服务端端口注册完毕!"); //通过此循环来遍例事件 while(true) { //查询事件如果一个事件都没有就阻塞 selector.select(); //定义一个byte缓冲区来存储收发的数据 ByteBuffer echoBuffer = ByteBuffer.allocate(BUFFER_SIZE); //此循环遍例所有产生的事件 for (SelectionKey key : selector.selectedKeys()) { //如果产生的事件为接受客户端连接(当有客户端连接服务器的时候产生) if((key.readyOps() & SelectionKey.OP_ACCEPT)==SelectionKey.OP_ACCEPT) { selector.selectedKeys().remove(key); //定义一个服务器socket通道 ServerSocketChannel subssc = (ServerSocketChannel)key.channel(); //将临时socket对象实例化为接收到的客户端的socket sc = subssc.accept(); //将客户端的socket设置为异步 sc.configureBlocking(false); //将客户端的socket的读取事件注册到事件选择器中 sc.register(selector, SelectionKey.OP_READ); //将本此事件从迭带器中删除 System.out.println("服务端有新连接:" + sc); } //如果产生的事件为读取数据(当已连接的客户端向服务器发送数据的时候产生) else if((key.readyOps()&SelectionKey.OP_READ)==SelectionKey.OP_READ) { //将本次事件删除 selector.selectedKeys().remove(key); //临时socket对象实例化为产生本事件的socket sc = (SocketChannel) key.channel(); //定义一个用于存储byte数据的流对象 ByteArrayOutputStream bos = new ByteArrayOutputStream(); //先将客户端的数据清空 echoBuffer.clear(); //a为读取到数据的长度 try { //循环读取所有客户端数据到byte缓冲区中,当有数据的时候read函数返回数据长度 //NIO会自动的将缓冲区一次容纳不下的自动分段 int readInt = 0; while ((readInt = sc.read(echoBuffer)) > 0) { //如果获得数据长度比缓冲区大小小的话 if (readInt<echoBuffer.capacity()) { //建立一个临时byte数组,将齐长度设为获取的数据的长度 byte[] readByte=new byte[readInt]; //循环向此临时数组中添加数据 for(int i=0;i<readInt;i++) { readByte[i]=echoBuffer.get(i); } //将此数据存入byte流中 bos.write(readByte); } //否则就是获得数据长度等于缓冲区大小 else { //将读取到的数据写入到byte流对象中 bos.write(echoBuffer.array()); } //将缓冲区清空,以便进行下一次存储数据 echoBuffer.clear(); } //当循环结束时byte流中已经存储了客户端发送的所有byte数据 System.out.println("服务端接收数据: "+new String(bos.toByteArray())); } catch(Exception e) { //当客户端在读取数据操作执行之前断开连接会产生异常信息 e.printStackTrace(); //将本socket的事件在选择器中删除 key.cancel(); break; } //获取byte流对象的标准byte对象 //byte[] b=bos.toByteArray(); String resp = "server data"; byte[] b = resp.getBytes(); //建立这个byte对象的ByteBuffer,并将数据存入 ByteBuffer byteBuffer = ByteBuffer.allocate(b.length); byteBuffer.put(b); //向客户端写入收到的数据 Write(byteBuffer); //关闭客户端连接 sc.close(); //将本socket的事件在选择器中删除 key.cancel(); System.out.println("服务端连接结束"); System.out.println("============================="); } } } } catch (Exception e) { e.printStackTrace(); } } public boolean Write(ByteBuffer echoBuffer) { //将缓冲区复位以便于进行其他读写操作 echoBuffer.flip(); try { //向客户端写入数据,数据为接受到数据 sc.write(echoBuffer); } catch (IOException e) { e.printStackTrace(); return false; } System.out.println("服务端返回数据: "+new String(echoBuffer.array())); return true; } } public class TestServer { public static void main(String args[]) { new AsynServer().start(); } }
客户端
package com.test.client; import java.io.ByteArrayOutputStream; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; class AsynClient { static private int BUFFER_SIZE = 256; public void start() { try { //定义一个记录套接字通道事件的对象 Selector selector = Selector.open(); //定义一个服务器地址的对象 SocketAddress address = new InetSocketAddress("localhost", 55555); //定义异步客户端 SocketChannel client = SocketChannel.open(address); //将客户端设定为异步 client.configureBlocking(false); //在轮讯对象中注册此客户端的读取事件(就是当服务器向此客户端发送数据的时候) client.register(selector, SelectionKey.OP_READ); //要发送的数据 String content = "client data"; byte[] sendBytes = content.getBytes(); //定义用来存储发送数据的byte缓冲区 ByteBuffer sendbuffer = ByteBuffer.allocate(sendBytes.length); //定义用于接收服务器返回的数据的缓冲区 ByteBuffer readBuffer = ByteBuffer.allocate(BUFFER_SIZE); //将数据put进缓冲区 sendbuffer.put(sendBytes); //将缓冲区各标志复位,因为向里面put了数据标志被改变要想从中读取数据发向服务器,就要复位 sendbuffer.flip(); //向服务器发送数据 client.write(sendbuffer); System.out.println("客户端发送数据: " + new String(sendbuffer.array())); //利用循环来读取服务器发回的数据 while (true) { //如果客户端连接没有打开就退出循环 if (!client.isOpen()) break; //此方法为查询是否有事件发生如果没有就阻塞,有的话返回事件数量 int shijian = selector.select(); //如果没有事件返回循环 if (shijian==0) { continue; } //定义一个临时的客户端socket对象 SocketChannel sc; //遍例所有的事件 for (SelectionKey key : selector.selectedKeys()) { //删除本次事件 selector.selectedKeys().remove(key); //如果本事件的类型为read时,表示服务器向本客户端发送了数据 if (key.isReadable()) { //将临时客户端对象实例为本事件的socket对象 sc = (SocketChannel) key.channel(); //定义一个用于存储所有服务器发送过来的数据 ByteArrayOutputStream bos = new ByteArrayOutputStream(); //将缓冲区清空以备下次读取 readBuffer.clear(); int readInt = 0; //此循环从本事件的客户端对象读取服务器发送来的数据到缓冲区中 while ((readInt = sc.read(readBuffer)) > 0) { if (readInt<readBuffer.capacity()) { //建立一个临时byte数组,将齐长度设为获取的数据的长度 byte[] readByte=new byte[readInt]; //循环向此临时数组中添加数据 for(int i=0;i<readInt;i++) { readByte[i]=readBuffer.get(i); } //将此数据存入byte流中 bos.write(readByte); } //将缓冲区清空以备下次读取 readBuffer.clear(); } //如果byte流中存有数据 if (bos.size() > 0) { //建立一个普通字节数组存取缓冲区的数据 byte[] recvBytes = bos.toByteArray(); System.out.println("客户端接收数据: " + new String(recvBytes)); //关闭客户端连接,此时服务器在read读取客户端信息的时候会返回-1 client.close(); System.out.println("客户端连接关闭!"); } } } } } catch(Exception e) { e.printStackTrace(); } } } public class TestClient { public static void main(String args[]) { new AsynbClient().start(); } }
最新文章
- 小兔JS教程(四)-- 彻底攻略JS数组
- Jquery.load() 使用
- 来自于2016.2.24的flag
- 重置mysql数据库密码相关方法
- 【HAPPY FOREST】用Unreal Engine4绘制实时CG影像
- nyoj 96 n-1位数(处理前导 0 的情况)
- 《wc》-linux命令五分钟系列之十七
- actionscript sendToURL请求url,传递http_referer分浏览器统计
- filestream 读取视频文件
- TEXT文本编辑框4 点击按钮读取文本框内容到内表
- 精讚部落::MySQL 的MEMORY engine
- Asp.Net Core轻量级Aop解决方案:AspectCore
- 我的Python学习笔记(二):浅拷贝和深拷贝
- HDU 1248 寒冰王座(完全背包裸题)
- sql中的case when then else end
- python 中numpy中函数hstack用法和作用
- python中文编码&;json中文输出问题
- How to use Jackson to deserialise an array of objects
- jenkins之另辟蹊径实现根据svn项目实现智能选择
- 防EasyUI中登录按钮