一、网络IO TCP
服务端代码
package com.sid.io.niov2;
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 NIOServer {
// 通道管理器
private Selector selector;
/**
* 获得一个ServerSocket通道,并对该通道做一些初始化的工作
* @param port 绑定的端口号
* @throws IOException
*/
public void initServer(int port) throws IOException {
// 获得一个ServerSocketChannel通道
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
// 设置通道为非阻塞
serverSocketChannel.configureBlocking(false);
// 将该通道对应的ServerSocket绑定到port端口
serverSocketChannel.bind(new InetSocketAddress(port));
// 获得一个通道管理器
this.selector = Selector.open();
// 将通道管理器和该通道绑定,并为该通道注册SelectionKey.OP_ACCEPT事件,注册该事件后,
// 当该事件到达时,selector.select()会返回,如果该事件没到达selector.select()会一直阻塞。
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
}
/**
* 采用轮询的方式监听selector上是否有需要处理的事件,如果有,则进行处理
* @throws IOException
*/
public void listen() throws IOException {
System.out.println("服务端启动成功!");
// 轮询访问selector
while (true) {
// 当注册的事件到达时,方法返回;否则,该方法会一直阻塞
selector.select();
// 获得selector中选中的项的迭代器,选中的项为注册的事件
Iterator<SelectionKey> ite = this.selector.selectedKeys().iterator();
while (ite.hasNext()) {
SelectionKey key = (SelectionKey) ite.next();
// 删除已选的key,以防重复处理
ite.remove();
if (key.isAcceptable()) {// 客户端请求连接事件
ServerSocketChannel server = (ServerSocketChannel) key.channel();
// 获得和客户端连接的通道
SocketChannel channel = server.accept();
// 设置成非阻塞
channel.configureBlocking(false);
// 在这里可以给客户端发送信息哦
channel.write(ByteBuffer.wrap(new String("服务端已经收到了你的连接")
.getBytes("utf-8")));
// 在和客户端连接成功之后,为了可以接收到客户端的信息,需要给通道设置读的权限。
channel.register(this.selector, SelectionKey.OP_READ);
} else if (key.isReadable()) {// 获得了可读的事件
read(key);
}
}
}
}
/**
* 处理读取客户端发来的信息 的事件
*
* @param key
* @throws IOException
*/
public void read(SelectionKey key) throws IOException {
// 服务器可读取消息:得到事件发生的Socket通道
SocketChannel channel = (SocketChannel) key.channel();
// 创建读取的缓冲区
ByteBuffer buffer = ByteBuffer.allocate(512);
channel.read(buffer);
byte[] data = buffer.array();
String msg = new String(data).trim();
System.out.println("服务端收到信息:" + msg);
ByteBuffer outBuffer = ByteBuffer.wrap(msg.getBytes("utf-8"));
channel.write(outBuffer);// 将消息回送给客户端
}
/**
* 启动服务端测试
*
* @throws IOException
*/
public static void main(String[] args) throws IOException {
NIOServer server = new NIOServer();
server.initServer(8000);
server.listen();
}
}
客户端
package com.sid.io.niov2;
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;
public class NIOClient {
//通道管理器
private Selector selector;
/**
* 获得一个Socket通道,并对该通道做一些初始化的工作
* @param ip 连接的服务器的ip
* @param port 连接的服务器的端口号
* @throws IOException
*/
public void initClient(String ip,int port) throws IOException {
// 获得一个Socket通道
SocketChannel channel = SocketChannel.open();
// 设置通道为非阻塞
channel.configureBlocking(false);
// 获得一个通道管理器
this.selector = Selector.open();
// 客户端连接服务器,其实方法执行并没有实现连接,需要在listen()方法中调
//用channel.finishConnect();才能完成连接
channel.connect(new InetSocketAddress(ip,port));
//将通道管理器和该通道绑定,并为该通道注册SelectionKey.OP_CONNECT事件。
channel.register(selector, SelectionKey.OP_CONNECT);
}
/**
* 采用轮询的方式监听selector上是否有需要处理的事件,如果有,则进行处理
* @throws IOException
*/
public void connect() throws IOException {
// 轮询访问selector
while (true) {
// 选择一组可以进行I/O操作的事件,放在selector中,客户端的该方法不会阻塞(测试的时候发现阻塞了),
//这里和服务端的方法不一样,查看api注释可以知道,当至少一个通道被选中时,
//selector的wakeup方法被调用,方法返回,而对于客户端来说,通道一直是被选中的
selector.select();
// 获得selector中选中的项的迭代器
Iterator<SelectionKey> ite = this.selector.selectedKeys().iterator();
while (ite.hasNext()) {
SelectionKey key = (SelectionKey) ite.next();
// 删除已选的key,以防重复处理
ite.remove();
// 连接事件发生
if (key.isConnectable()) {
SocketChannel channel = (SocketChannel) key.channel();
// 如果正在连接,则完成连接
if(channel.isConnectionPending()){
channel.finishConnect();
}
// 设置成非阻塞
channel.configureBlocking(false);
//在这里可以给服务端发送信息哦
channel.write(ByteBuffer.wrap(new String("向服务端发送了一条信息").getBytes("utf-8")));
//在和服务端连接成功之后,为了可以接收到服务端的信息,需要给通道设置读的权限。
channel.register(this.selector, SelectionKey.OP_READ); // 获得了可读的事件
} else if (key.isReadable()) {
read(key);
}
}
}
}
/**
* 处理读取服务端发来的信息 的事件
* @param key
* @throws IOException
*/
public void read(SelectionKey key) throws IOException{
//和服务端的read方法一样
// 服务器可读取消息:得到事件发生的Socket通道
SocketChannel channel = (SocketChannel) key.channel();
// 创建读取的缓冲区
ByteBuffer buffer = ByteBuffer.allocate(512);
channel.read(buffer);
byte[] data = buffer.array();
String msg = new String(data).trim();
System.out.println("客户端收到信息:" + msg);
//ByteBuffer outBuffer = ByteBuffer.wrap(msg.getBytes("utf-8"));
//channel.write(outBuffer);// 将消息回送给客户端
}
/**
* 启动客户端测试
* @throws IOException
*/
public static void main(String[] args) throws IOException {
NIOClient client = new NIOClient();
client.initClient("localhost",8000);
client.connect();
}
}
二、网络IO UDP
由于udp是一个无连接的协议,因此服务器端和客户端的代码基本相同。实际上服务器和客户端之间并没有太大区分。所以不存在ServerDatagramChannel这种玩意了,服务器端和客户端都是创建一个DatagramChannel。然后bind一个端口,注册Selector之后就可以打开监听了。
服务端
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
import java.util.Set;
public class NIOUdpServer implements Runnable {
private int port;
public NIOUdpServer(int port) {
this.port = port;
new Thread(this).start();
}
public void run() {
try {
// 建立
DatagramChannel dc = DatagramChannel.open();
dc.configureBlocking(false);
SocketAddress address = new InetSocketAddress(port);
// 本地绑定端口
DatagramSocket ds = dc.socket();
ds.setReceiveBufferSize(20480);
ds.bind(address);
// 注册
Selector select = Selector.open();
dc.register(select, SelectionKey.OP_READ);
System.out.println("Listening on port " + port);
ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
int number = 0; // 只为记录接受的字节数
while (true) {
int num = select.select();
// 如果选择器数目为0,则结束循环
if (num == 0) {
continue;
}
// 得到选择键列表
Set Keys = select.selectedKeys();
Iterator it = Keys.iterator();
while (it.hasNext()) {
SelectionKey k = (SelectionKey) it.next();
if ((k.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
DatagramChannel cc = (DatagramChannel) k.channel();
// 非阻塞
cc.configureBlocking(false);
// 接收数据并读到buffer中
buffer.clear();
SocketAddress client = cc.receive(buffer);
buffer.flip();
if (buffer.remaining() <= 0) {
System.out.println("bb is null");
}
// 记录接收到的字节总数
number += buffer.remaining();
byte b[] = new byte[buffer.remaining()];
for (int i = 0; i < buffer.remaining(); i++) {
b[i] = buffer.get(i);
}
String in = new String(b, "gb2312");
System.out.println("number::::" + number);
// 执行操作,并回发送
}
}
Keys.clear();
}
} catch (IOException ie) {
System.err.println(ie);
}
}
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
int port = 1111;
new NIOUdpServer(port);
}
}
客户端
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
public class NIOUdpClient extends Thread {
private String host;
private int port;
int j = 0;
int number;
public NIOUdpClient(String host, int port, int numThreads) {
this.host = host;
this.port = port;
for (int i = 0; i < numThreads; ++i) {
new Thread(this).start();
}
}
public void run() {
// 构造一个数据报Socket
DatagramChannel dc = null;
try {
dc = DatagramChannel.open();
} catch (IOException ex4) {
}
SocketAddress address = new InetSocketAddress(host, port);
try {
dc.connect(address);
} catch (IOException ex) {
}
// 发送请求
ByteBuffer bb = ByteBuffer.allocate(130);
byte[] b = new byte[130];
String s = "sdfas";
s = "sss";
b = s.getBytes();
bb.clear();
bb.put(b);
bb.flip();
// 测试
if (bb.remaining() <= 0) {
System.out.println("bb is null");
}
try {
int num = dc.send(bb, address);
number = number + num;
System.out.println("number:::" + number);
bb.clear();
dc.receive(bb);
bb.flip();
byte[] by = new byte[bb.remaining()];
for (int i = 0; i < bb.remaining(); i++) {
by[i] = bb.get(i);
}
String ss = new String(by, "gb2312");
System.out.println(ss);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param args
*/
public static void main(String[] args) {
String host = "127.0.0.1";
int port = 1111;
int numThreads = 3;
new NIOUdpClient(host, port, numThreads);
}
}
三、本地文件IO
package com.sid.io.niov2;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class NIOFileCopy {
public static void fileCopyByNIO(String resource,String destination) throws Exception{
FileInputStream fileInputStream = new FileInputStream(resource);
FileOutputStream fileOutputStream = new FileOutputStream(destination);
FileChannel fileReadChannel = fileInputStream.getChannel();
FileChannel fileWriteChannel = fileOutputStream.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.clear();
int len = 0;
while((len=fileReadChannel.read(buffer))!=-1){
buffer.flip();
fileWriteChannel.write(buffer);
buffer.clear();
}
fileReadChannel.close();
fileWriteChannel.close();
}
public static void operFileMapped(String file) throws Exception{
RandomAccessFile raf = new RandomAccessFile(file, "rw");
FileChannel fc = raf.getChannel();
MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, 0, raf.length());
/*
while(mbb.hasRemaining()){
System.out.println((char)mbb.get());
}
*/
byte index0 = mbb.get(0);
System.out.println(index0);
mbb.put(0,(byte)-119);
raf.close();
}
public static void main(String[] args) {
/*
try {
NIOFileCopy.fileCopyByNIO("D:\\projects\\testWeb\\src\\zmx\\nio\\test\\test.txt", "D:\\projects\\testWeb\\src\\zmx\\nio\\test\\copy.txt");
} catch (Exception e) {
e.printStackTrace();
}
*/
try {
NIOFileCopy.operFileMapped("D:\\projects\\testWeb\\src\\zmx\\nio\\test\\yumi.png");
} catch (Exception e) {
e.printStackTrace();
}
}
}