Netty
1.介绍
Netty是由JBOSS提供的一个java开源框架,现为 Github上的独立项目。Netty是一个异步的,基于事件驱动开发的网络应用框架用于开发高性能,高可靠性的网络IO程序。
也就是说,Netty 是一个基于NIO的客户、服务器端的编程框架,使用Netty 可以确保你快速和简单的开发出一个网络应用,例如实现了某种协议的客户、服务端应用。Netty相当于简化和流线化了网络应用的编程开发过程,例如:基于TCP和UDP的socket服务开发。
2.BIO
BIO是(Block IO)即阻塞IO,是java最初的IO模型,JDK1.4之前唯一选择。
BIO中主要角色就是Server(可以自己写Client),必须使用多线程。每次有客户端连接都要新建一个线程,去单独处理这个线程。
Server
package bio;import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;public class Server {public static void main(String[] args) throws IOException {ServerSocket serverSocket = null;//服务端绑定端口serverSocket = new ServerSocket(9000);System.out.println("等待连接......");//阻塞接收客户端while (true){Socket client = serverSocket.accept();//直接创建线程new Thread(new Runnable() {@Overridepublic void run() {//System.out.println("连接成功");String msg = null;try {msg = handle(client);} catch (IOException e) {e.printStackTrace();}System.out.println("接收到的数据:"+msg);}}).start();}}public static String handle(Socket clientSocket) throws IOException {byte buffer[] = new byte[1024];String msg = null;int len = clientSocket.getInputStream().read(buffer);if(len != -1){msg = new String(buffer,0,len,"utf-8");}return msg;}}
Client
package bio;import java.io.IOException;import java.io.OutputStream;import java.net.Socket;public class Client {public void sendMsg(String name){Socket socket = null;try {socket = new Socket("localhost",9000);String msg = "这是来自"+name+"的消息";byte[] buffer = msg.getBytes("utf-8");OutputStream outputStream = socket.getOutputStream();outputStream.write(buffer);outputStream.close();socket.close();} catch (IOException e) {e.printStackTrace();}}}
建立10个客户端通信
package bio;import java.util.Random;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class Clients {public static void main(String[] args) throws InterruptedException {// for (int i = 0; i < 5; i++) {// //Thread.sleep(1000);// int index = i;// new Thread(new Runnable() {// @Override// public void run() {// new Client().sendMsg("xiao"+index);// }// }).start();// }/*** 线程池版本*/ExecutorService executorService = Executors.newFixedThreadPool(10);for (int i = 0; i < 10; i++) {executorService.submit(new Runnable() {@Overridepublic void run() {new Client().sendMsg("xiao"+new Random().nextInt(99));}});}}}
3.NIO
3.1.组件关系
- 每个 channel 都会对应一个 Buffer
- 一个线程对应一个Selector , 一个Selector对应多个 channel(连接)
- 程序切换到哪个 channel 是由事件决定的
- Selector 会根据不同的事件,在各个通道上切换
- Buffer 就是一个内存块 , 底层是一个数组
- 数据的读取写入是通过 Buffer完成的 ,BIO 中要么是输入流,或者是输出流, 不能双向,但是 NIO 的 Buffer 是可以读也可以写。
- Java NIO系统的核心在于:通道(Channel)和缓冲区 (Buffer)。通道表示打开到 IO 设备(例如:文件、 套接字)的连接。若需要使用 NIO 系统,需要获取用于连接 IO 设备的通道以及用于容纳数据的缓冲区。然后操作缓冲区,对数据进行处理。简而言之,Channel 负责传输, Buffer 负责存取数据
3.2.Buffer
缓冲区Buffer,实质上是一个可以读写数据的内存块,可以理解为是一个容器对象(含数组),该对象提供一组方法,可以轻松使用内存块,缓冲区对选哪个内置了一些机制,能够跟踪和记录缓冲区的状态变化,Channel提供从文件,网络读取数据的渠道,但是读取或写入的数据必须经由Buffer
Buffer4个属性
private int mark = -1;private int position = 0;private int limit;private int capacity;
| 属性 | 描述 |
|---|---|
| mark | 标记 |
| position | 位置,下一个要读或写的元素的索引,每次读写缓冲区都会改变当前值,以便下次读写。 |
| limit | 表示缓冲区的当前终点,不能对缓冲区超过极限的位置进行读写,且极限是可以修改的。 |
| Capacity | 当前缓冲区的容量,在缓冲区创建时确定并不能修改。 |
0<=mark<=position<=limit<=capacity
package nioBasic;import java.nio.IntBuffer;public class Buffer1 {public static void main(String[] args) {//声明一个10个大小的intBufferIntBuffer intBuffer = IntBuffer.allocate(10);for (int i = 0; i < 10; i++) {//在intBuffer中放入元素intBuffer.put(i*10);}/**public final Buffer flip() {limit = position;position = 0;mark = -1;return this;}在一次完整的读或写操作后position == limit,需要归零,注意不是回到最初的状态limit == position[而是limit等于存放的数据的长度]*/intBuffer.flip();while (intBuffer.hasRemaining()/*判断当前position<limit*/){System.out.println(intBuffer.get());}}}
3.3.Channel
Channel 经常翻译为通道,类似 IO 中的流,用于读取和写入。它与前面介绍的 Buffer 打交道,读操作的时候将 Channel 中的数据填充到 Buffer 中,而写操作时将 Buffer 中的数据写入到 Channel 中
- FileChannel用于对文件的数据读写
- SocketChannel与ServerSocketChannel对应Socket与ServerSocket,用于TCP通信
- DatagramChannel用于UDP通信
FileChannel实验
实验1:通过nio向文件中输出内容
package nioBasic;/*** 通过nio向文件中输出内容*/import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;public class Channel1 {public static void main(String[] args) throws IOException {//创建一个测试文件File file = new File("nioTest1.txt");if (!file.exists()){file.createNewFile();}//获取文件输出流FileOutputStream fos = new FileOutputStream(file);//获取文件输出流的ChannelFileChannel channel = fos.getChannel();//创建一个BufferByteBuffer msg = ByteBuffer.wrap("Hello,肖云飞\n".getBytes());//将Buffer的内容写到Channel中,由于这个Channel与指定文件绑定,所以会写到文件中channel.write(msg);fos.close();}}
实验二乐观版本:
package nioBasic;import java.io.FileInputStream;import java.io.IOException;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;public class Channel2_1 {public static void main(String[] args) throws IOException {FileInputStream fis = new FileInputStream("nioTest1.txt");FileChannel channel = fis.getChannel();/*** 实现预知到文件内容小于1024字节*/ByteBuffer buffer = ByteBuffer.allocate(1024);int read = channel.read(buffer);String msg = new String(buffer.array());System.out.println(msg);fis.close();}}
实验二悲观版本
package nioBasic;/*** 通过nio从文件中获取内容*/import java.io.FileInputStream;import java.io.IOException;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;import java.util.ArrayList;import java.util.List;public class Channel2_2 {public static void main(String[] args) throws IOException {FileInputStream fis = new FileInputStream("nioTest1.txt");FileChannel channel = fis.getChannel();//初始化一个大小为10的ByteBuffer/*** 注意,这个FileInputStream内置的Channel(FileChannel)是特殊的,只能使用ByteBuffer* public abstract class FileChannel* extends AbstractInterruptibleChannel* implements SeekableByteChannel, GatheringByteChannel, ScatteringByteChannel{...}*/ByteBuffer buffer = ByteBuffer.allocate(10);List<Byte> bytes = new ArrayList<>();while (true){/*** 注意:当buffer不能一次把所有的内容读完必须要有这句话* 如果没有,第一次读完后position == limit,到极限了,之后每次都会读到0个,就会死循环**/buffer.clear();int read = channel.read(buffer);if(read == -1){break;}else{/*** 现在我们无法预测文件的大小,所以不能确保Buffer的大小,* 所以“悲观地”认为Buffer无法一次读完,这种情况下需要拼接** 但是有个问题,我们每次读可以得到一个ByteBuffer,里面是n个Byte,* 使用StringBuilder拼接的话append方法不能传入byte类型,只能是Char* 但如果使用char的话极有可能使中文字符(占三个字节)被分割开,出现乱码,* 所以需要将所有的ByteBuffer转化为byte[]后拼接为一个大的byte[],再转化为String*/byte[] array = buffer.array();for (int i = 0; i < read; i++) {bytes.add(array[i]);}}}/*** 将List<byte>转化为byte[],方便转化为字符串*/byte[] msgArray = new byte[bytes.size()];for (int i = 0; i < bytes.size(); i++) {msgArray[i] = bytes.get(i);}System.out.println(new String(msgArray));fis.close();}}
MappedByteBuffer
MappedByteBuffer是ByteBuffer的子类,特点是首先它是针对RandomAccessFile使用的,所以是内存直接映射文件的,其次,它对RandomAccessFile功能进一步升级,可以指定映射的范围
package nioBasic;import java.io.IOException;import java.io.RandomAccessFile;import java.nio.MappedByteBuffer;import java.nio.channels.FileChannel;public class MappedByteBufferTest {public static void main(String[] args) throws IOException {/*** 创建随机读写文件(这个类只能操作文件)* 随机读写文件的特点是可以把文件的操作像操作数组一样,是以byte为单位的* 有一个特点是seek(long pos)方法,可以把文件的指针直接指向pos索引处开始操作*/RandomAccessFile raf = new RandomAccessFile("nioTest1.txt","rw");//获取channelFileChannel channel = raf.getChannel();/*** public abstract MappedByteBuffer map(MapMode mode,long position, long size)* 1.MapMode,这个Channel的操作模式(只读,读写,私有->写时复制)* 2.position,从哪个位置开始映射* 3.size,映射多少个块[多少个byte]** 这就是MappedByteBuffer的特点,可以只将文件中某一段内容映射到内存中操作*/MappedByteBuffer map = channel.map(FileChannel.MapMode.READ_WRITE, 0, 5);//先可以将所有的映射读取出来while (map.hasRemaining()){System.out.print((char)map.get());}//map.flip();System.out.println("\n========================");//修改内容map.put(0,(byte)'H');map.put(1,(byte)'e');map.put(2,(byte)'l');map.put(3,(byte)'l');map.put(4,(byte)'o');//map.put(5,(byte)'p');会抛出异常,因为size是大小,不是索引map.flip();while (map.hasRemaining()){System.out.print((char)map.get());}raf.close();}}/**结果hELLO========================Hello**/
3.4.Buffer的聚合与分散
分散/聚集 I/O 是使用多个而不是单个缓冲区来保存数据的读写方法。
一个分散的读取就像一个常规通道读取,只不过它是将数据读到一个缓冲区数组中而不是读到单个缓冲区中。同样地,一个聚集写入是向缓冲区数组而不是向单个缓冲区写入数据。
分散/聚集 I/O 对于将数据流划分为单独的部分很有用,这有助于实现复杂的数据格式。
ScatteringByteChannel、GatheringByteChannel 是两个interface,而 FileChannel 和 SocketChannel 等实现了这两个接口。
ScatteringByteChannel 是一个具有两个附加读方法的通道:
long read( ByteBuffer[] dsts );long read( ByteBuffer[] dsts, int offset, int length );
这些 long read() 方法很像标准的 read 方法,只不过它们不是取单个缓冲区而是取一个缓冲区数组。
在 分散读取 中,通道依次填充每个缓冲区。填满一个缓冲区后,它就开始填充下一个,在移动下一个buffer前,必须填满当前的buffer,这也意味着它不适用于动态消息(消息大小不固定)。在某种意义上,缓冲区数组就像一个大缓冲区。
GatheringByteChannel聚集写入 类似于分散读取,只不过是用来写入。它也有接受缓冲区数组的方法:
long write( ByteBuffer[] srcs );long write( ByteBuffer[] srcs, int offset, int length );
分散/聚集 I/O 对于将数据划分为几个部分很有用。例如,可能在编写一个使用消息对象的网络应用程序,每一个消息被划分为固定长度的头部和固定长度的正文。可以创建一个刚好可以容纳头部的缓冲区和另一个刚好可以容难正文的缓冲区。当您将它们放入一个数组中并使用分散读取来向它们读入消息时,头部和正文将整齐地划分到这两个缓冲区中。我们从缓冲区所得到的方便性对于缓冲区数组同样有效。因为每一个缓冲区都跟踪自己还可以接受多少数据,所以分散读取会自动找到有空间接受数据的第一个缓冲区。在这个缓冲区填满后,它就会移动到下一个缓冲区。聚集写对于把一组单独的缓冲区中组成单个数据流很有用。为了与上面的消息例子保持一致,可以使用聚集写入来自动将网络消息的各个部分组装为单个数据流,以便跨越网络传输消息。
3.5.Selector
选择器提供选择执行已经就绪的任务的能力。从底层来看,Selector提供了询问通道是否已经准备好执行每个I/O操作的能力。Selector 允许单线程处理多个Channel。仅用单个线程来处理多个Channels的好处是,只需要更少的线程来处理通道。事实上,可以只用一个线程处理所有的通道,这样会大量的减少线程之间上下文切换的开销。
并不是所有的Channel,都是可以被Selector 复用的。比方说,FileChannel就不能被选择器复用。
判断一个Channel 能被Selector 复用,有一个前提:判断他是否继承了一个抽象类SelectableChannel。如果继承了SelectableChannel,则可以被复用,否则不能。
SelectableChannel类提供了实现通道的可选择性所需要的公共方法。它是所有支持就绪检查的通道类的父类。所有socket通道,都继承了SelectableChannel类都是可选择的,包括从管道(Pipe)对象的中获得的通道。而FileChannel类,没有继承SelectableChannel,因此是不是可选通道。
3.6.nio服务端实例
package nio;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;import java.util.Set;public class ServerPro {public static void main(String[] args) throws IOException, InterruptedException {//对服务端配置ServerSocketChannel server = ServerSocketChannel.open();server.bind(new InetSocketAddress(9000));server.configureBlocking(false);//开启多路复用器Selector selector = Selector.open();//将服务端Channel以OP_ACCEPT方式注册到复用器里面server.register(selector, SelectionKey.OP_ACCEPT);System.out.println("等待连接......");while (true){//多路复用器开始阻塞等待是否有事件发生(任何事件都会跳出阻塞)selector.select();Set<SelectionKey> selectionKeys = selector.selectedKeys();Iterator<SelectionKey> channels = selectionKeys.iterator();while(channels.hasNext()){SelectionKey selectionKey = channels.next();{//如果是接收事件,说明是有客户连接服务端if (selectionKey.isAcceptable()){ServerSocketChannel serverTmp = (ServerSocketChannel)selectionKey.channel();//获取客户通道,配置为非阻塞SocketChannel accept = serverTmp.accept();accept.configureBlocking(false);//因为建立连接,认为其会有读事件发生accept.register(selector,SelectionKey.OP_READ);System.out.println("连接成功......");}//如果是可读事件,说明是客户端else if (selectionKey.isReadable()){ByteBuffer buffer = ByteBuffer.allocate(256);SocketChannel clientTmp = (SocketChannel) selectionKey.channel();int len = clientTmp.read(buffer);if(len > 0){String msg = new String(buffer.array(),0,len);System.out.println("接收到的消息:"+msg);if(msg.equals("通信完成,可以关闭")){if(!clientTmp.isConnected()){System.out.println("异常结束");}else if(clientTmp.isConnected()){selectionKey.cancel();System.out.println("通信完成");}}else{clientTmp.register(selector,SelectionKey.OP_WRITE);}}else if(len == -1){System.out.println("断开连接");selectionKey.cancel();}}else if(selectionKey.isWritable()){SocketChannel writeChannel = (SocketChannel)selectionKey.channel();writeChannel.write(ByteBuffer.wrap("已接收到客户端消息。".getBytes()));writeChannel.register(selector,SelectionKey.OP_READ);//Thread.sleep(2000);}channels.remove();}}}}}
3.7.nio客户端实例
package nio;import java.io.IOException;import java.net.InetSocketAddress;import java.nio.ByteBuffer;import java.nio.channels.*;import java.util.Iterator;import java.util.Set;public class Client {public void sendMsg(Selector selector,SocketChannel socket,String name) throws IOException, InterruptedException {//SocketChannel socket = SocketChannel.open();//Selector selector = Selector.open();socket.configureBlocking(false);socket.register(selector, SelectionKey.OP_CONNECT);socket.connect(new InetSocketAddress("localhost",9000));while(true){selector.select();Set<SelectionKey> selectionKeys = selector.selectedKeys();Iterator<SelectionKey> channels = selectionKeys.iterator();while (channels.hasNext()){SelectionKey channel = channels.next();if(channel.isConnectable()){//while(!socket.connect(new InetSocketAddress("localhost",9000)));/*** 下面这个判断是判断连接是否正在进行,不是必要的* 但是这个循环是必要的,直到socket.finishConnect()返回true才说明连接成功* 当然,在socket.finishConnect()返回false的阶段,客户端可以做其他事*///if(socket.isConnectionPending()){while(!socket.finishConnect());//}//if(socket.finishConnect()){String msg = name + "的消息";byte[] bytes = msg.getBytes("utf-8");ByteBuffer buffer = ByteBuffer.wrap(bytes);socket.write(buffer);//channel.cancel();socket.register(selector,SelectionKey.OP_READ);//}}else if(channel.isReadable()){SocketChannel serverTmp = (SocketChannel)channel.channel();ByteBuffer buffer = ByteBuffer.allocate(256);int len = serverTmp.read(buffer);if(len > 0){String msg = (new String(buffer.array(),0,len).split("。"))[0];//System.out.println(msg.length());//System.out.println("已接收到客户端消息".length());System.out.println(msg);if(msg.equals("已接收到客户端消息")){System.out.println("正在关闭......");serverTmp.write(ByteBuffer.wrap("通信完成,可以关闭".getBytes()));//这里休眠2秒是为了确保服务端能正常关闭通道Thread.sleep(2000);System.exit(0);}}else if (len == -1){System.out.println("连接断开");channel.cancel();}}channels.remove();}}}}
3.8.多客户端运行(多线程)
package nio;import java.io.IOException;import java.nio.channels.Selector;import java.nio.channels.SocketChannel;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class Clients {public static void main(String[] args) throws IOException {ExecutorService executorService = Executors.newCachedThreadPool();for (int i = 0; i < 10; i++) {String id = new Integer(i).hashCode()+"";executorService.execute(new Runnable() {@Overridepublic void run() {try {//让每个客户端channel都持有一个selectorSocketChannel channel = SocketChannel.open();Selector selector = Selector.open();new Client().sendMsg(selector,channel,"肖云飞"+id);} catch (IOException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();}}});}}}
3.9.小实战
nio实现群聊系统
服务端
package nio.groupChat;import java.io.IOException;import java.net.InetSocketAddress;import java.nio.ByteBuffer;import java.nio.channels.*;import java.util.Iterator;import java.util.Set;public class ChatServer {private Selector selector = null;private ServerSocketChannel serverSocketChannel = null;private final int port = 9000;//初始化属性public ChatServer(){try {selector = Selector.open();serverSocketChannel = ServerSocketChannel.open();serverSocketChannel.socket().bind(new InetSocketAddress(port));serverSocketChannel.configureBlocking(false);serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);} catch (IOException e) {e.printStackTrace();}}public void listen() throws IOException {while (true){int sum = selector.select(10000);if(sum > 0){Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();while (iterator.hasNext()){SelectionKey key = iterator.next();if(key.isAcceptable()){SocketChannel client = serverSocketChannel.accept();client.configureBlocking(false);client.register(selector,SelectionKey.OP_READ);System.out.println(client.getRemoteAddress()+"上线");}else if(key.isReadable()){SocketChannel client = (SocketChannel) key.channel();Boolean flag = true;//读取并广播readAndBroadcast(client,flag);System.out.println();}iterator.remove();}}else{continue;//System.out.println("无连接");}}}/*** 从指定客户端读取消息* @param client 客户顿* @param flag 标志,表示是否可以继续读*/private void readAndBroadcast(SocketChannel client,Boolean flag){while (flag) {ByteBuffer buffer = ByteBuffer.allocate(1024);String msg = null;try {int read = client.read(buffer);if (read > 0) {msg = new String(buffer.array());System.out.println(client.getRemoteAddress()+"说:"+msg);//接收到消息后广播broadCast(msg,client);} else {//没有消息说明已经不用读了,但通道不用注销flag = false;}} catch (IOException e) {try {System.out.println("客户端" + client.getRemoteAddress() + "已下线");//出现异常,关闭通道flag = false;client.close();} catch (IOException ex) {ex.printStackTrace();}}}}/*** 广播消息* @param msg 消息* @param self 广播对象需要排除自己*/private void broadCast(String msg,SocketChannel self) throws IOException {/*** 广播不需要selector.select()了,直接遍历所有注册到selector的key* 遍历排除serverSocketChannel与自己* 发送消息*/Set<SelectionKey> keys = selector.keys();for (SelectionKey key : keys) {SelectableChannel channel = key.channel();if (channel instanceof SocketChannel && channel != self) {SocketChannel client = (SocketChannel)channel;String endMag = "["+self.getRemoteAddress()+"]->"+msg;ByteBuffer buffer = ByteBuffer.wrap(endMag.getBytes());client.write(buffer);}}}public static void main(String[] args) throws IOException {new ChatServer().listen();}}
客户端
package nio.groupChat;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.SocketChannel;import java.util.Iterator;import java.util.Scanner;public class ChatClient {private Selector selector = null;private SocketChannel client = null;private static final String RemoveHost = "localhost";private static final int port = 9000;//初始化public ChatClient(){try {selector = Selector.open();client = SocketChannel.open();client.configureBlocking(false);//初始注册为SelectionKey.OP_CONNECTclient.register(selector, SelectionKey.OP_CONNECT);client.connect(new InetSocketAddress(RemoveHost,port));} catch (IOException e) {e.printStackTrace();}}/*** 确保客户端的连接成功* @throws IOException*/public void connect() throws IOException {selector.select();Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();while (iterator.hasNext()){SelectionKey key = iterator.next();if(key.isConnectable()){while (!client.finishConnect());client.register(selector,SelectionKey.OP_READ);}}}public void write() throws IOException {//必须等到连接建立,如果先调用了上面的connect方法就不需要了//while (!client.finishConnect());/*** 确定连接建立后,就把原来的CONNECT改注册为READ*///client.register(selector,SelectionKey.OP_READ);//发消息while (true){Scanner scanner = new Scanner(System.in);String msg = scanner.nextLine();ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());try {client.write(buffer);} catch (IOException e) {e.printStackTrace();}}}public void readInfo() throws IOException {//必须等到连接建立,如果先调用了上面的connect方法就不需要了//while (!client.finishConnect());/*** 确定连接建立后,就把原来的CONNECT改注册为READ*///client.register(selector,SelectionKey.OP_READ);try {while (true){int sum = selector.select(2000);if(sum > 0){Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();while (iterator.hasNext()){SelectionKey key = iterator.next();if(key.isReadable()){ByteBuffer buffer = ByteBuffer.allocate(1024);int read = client.read(buffer);//System.out.print("接收到消息:");System.out.println(new String(buffer.array()));}iterator.remove();}}else {continue;}}} catch (IOException e) {e.printStackTrace();}}}
客户端开通
package nio.groupChat;import java.io.IOException;public class Client0 {public static void main(String[] args) throws IOException {ChatClient chatClient0 = new ChatClient();//如果在write()与readInfo()里面加了确保连接以及修改注册的语句,就可以不用connect()了/*** 但是我发现由于初始注册的是CONNECT,就需要在建立连接后修改注册为READ,否则无法接受消息* 如果不执行connect(),就需要在write()与readInfo()中都添加修改注册的语句* (因为不能确保当前客户端先执行write()),这样会重复执行两次,不是很好*/chatClient0.connect();new Thread(new Runnable() {@Overridepublic void run() {try {chatClient0.write();} catch (IOException e) {e.printStackTrace();}}}).start();new Thread(new Runnable() {@Overridepublic void run() {try {chatClient0.readInfo();} catch (IOException e) {e.printStackTrace();}}}).start();}}
package nio.groupChat;import java.io.IOException;public class Client1 {public static void main(String[] args) throws IOException {ChatClient chatClient1 = new ChatClient();/*** 确保连接建立*/chatClient1.connect();new Thread(new Runnable() {@Overridepublic void run() {try {chatClient1.write();} catch (IOException e) {e.printStackTrace();}}}).start();new Thread(new Runnable() {@Overridepublic void run() {try {chatClient1.readInfo();} catch (IOException e) {e.printStackTrace();}}}).start();}}
package nio.groupChat;import java.io.IOException;public class Client2 {public static void main(String[] args) throws IOException {ChatClient chatClient2 = new ChatClient();/*** 确保连接建立*/chatClient2.connect();new Thread(new Runnable() {@Overridepublic void run() {try {chatClient2.write();} catch (IOException e) {e.printStackTrace();}}}).start();new Thread(new Runnable() {@Overridepublic void run() {try {chatClient2.readInfo();} catch (IOException e) {e.printStackTrace();}}}).start();}}
3.10.零拷贝
在java程序中,常用的零拷贝实现有mmap(内存映射)和sendFile
关于零拷贝,在另一个md里面,下面是零拷贝在nio中的使用
NewIOClient
import java.io.FileInputStream;import java.io.IOException;import java.net.InetSocketAddress;import java.nio.channels.FileChannel;import java.nio.channels.SocketChannel;public class NewIOClient {public static void main(String[] args) throws IOException {SocketChannel socketChannel = SocketChannel.open();socketChannel.connect(new InetSocketAddress("localhost",4399));String filename="CodeForces.rar";//得到文件的channelFileChannel fileChannel = new FileInputStream(filename).getChannel();long startTimeMillis = System.currentTimeMillis();//在Linux下一个transto函数可以完成传输//在windows下一次调用只能发送8M的文件,需要分段传输文件,而且要注意传送时的位置//transferto底层用到零拷贝,传送到socketchannel中long transfercount = fileChannel.transferTo(0, fileChannel.size(), socketChannel);System.out.println("发送的字节数为:"+transfercount+",耗时为:" + (System.currentTimeMillis() - startTimeMillis));fileChannel.close();}}
NewIOServer
import java.io.IOException;import java.net.InetSocketAddress;import java.net.ServerSocket;import java.nio.ByteBuffer;import java.nio.channels.ServerSocketChannel;import java.nio.channels.SocketChannel;public class NewIOServer {public static void main(String[] args) throws IOException {InetSocketAddress inetSocketAddress = new InetSocketAddress(4399);ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();ServerSocket serverSocket = serverSocketChannel.socket();serverSocket.bind(inetSocketAddress);ByteBuffer byteBuffer = ByteBuffer.allocate(1024);while (true){SocketChannel socketChannel = serverSocketChannel.accept();int readacount=0;while (readacount != -1){try {readacount = socketChannel.read(byteBuffer);}catch (Exception e){break;}byteBuffer.rewind(); //将buffer的position置为0,mark作废}}}}
