Java NIO示例

给出Java NIO的示例。包含客户端和服务端。

示例

  • NIOServer.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;
/**
* NIOServer
*/
public class NIOServer {
private Selector selector;
ServerSocketChannel serverSocketChannel;
public void initServer(int port) throws IOException {
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().bind(new InetSocketAddress("localhost", port));
this.selector = Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
}
public void listen() throws IOException {
System.out.println("server started succeed!");
while (true) {
selector.select();
Iterator<SelectionKey> ite = selector.selectedKeys().iterator();
while (ite.hasNext()) {
SelectionKey key = ite.next();
if(key.isAcceptable()) {
SocketChannel channel = serverSocketChannel.accept();
channel.configureBlocking(false);
channel.register(selector, SelectionKey.OP_READ);
} else if(key.isReadable()) {
recvAndReply(key);
}
ite.remove();
}
}
}
public void recvAndReply(SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel)key.channel();
ByteBuffer buffer = ByteBuffer.allocate(256);
int i = channel.read(buffer);
if (i != -1) { //用于判断客户端是否断开了连接
String msg = new String(buffer.array()).trim();
System.out.println("server received message: " + msg);
System.out.println("server reply: " + msg);
channel.write(ByteBuffer.wrap(msg.getBytes()));
} else {
channel.close(); //如果客户端断开连接就关闭该连接
}
}
public static void main(String[] args) throws IOException {
NIOServer server = new NIOServer();
server.initServer(7788);
server.listen();
}
}
  • NIOClient.java
import java.io.IOError;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.NotYetConnectedException;
import java.nio.channels.SocketChannel;
import java.nio.ByteBuffer;
/**
* NIOClient
*/
public class NIOClient {
SocketChannel channel;
public void initClient(String host, int port) throws IOException {
InetSocketAddress servAddr = new InetSocketAddress(host, port);
this.channel = SocketChannel.open(servAddr);
}
public void sendAndRecv(String words) throws IOException {
byte[] msg = new String(words).getBytes();
ByteBuffer buffer = ByteBuffer.wrap(msg);
System.out.println("sending: " + words);
channel.write(buffer);
buffer.clear();
channel.read(buffer);
System.out.println("received: " + new String(buffer.array()).trim());
buffer.clear();
System.out.println("sending: " + "again");
buffer = ByteBuffer.wrap(new String("again").getBytes());
channel.write(buffer);
buffer.clear();
channel.read(buffer);
System.out.println("received: " + new String(buffer.array()).trim());
channel.close();
}
public static void main(String[] args) throws IOException{
NIOClient client = new NIOClient();
client.initClient("localhost", 7788);
client.sendAndRecv("this is client");
}
}

运行

程序运行顺序如下:

  1. 运行NIOServer
  2. 运行NIOClient

输出

  • NIOServer
server started succeed!
server received message: this is client
server reply: this is client
server received message: again
server reply: again
  • NIOClient
sending: this is client
received: this is client
sending: again
received: again
Process finished with exit code 0

欢迎关注公众号: FullStackPlan 获取更多干货

Copyright © 2016 - 2017 LBD's Blog All Rights Reserved.

访客数 : | 访问量 :