服务端
package com.mang.NIO.nsync;
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;
public class EchoServer {
private Selector selector = null;
private ServerSocketChannel serverSocketChannel = null;
private int port = 8000;
private Charset charset = Charset.forName("GBK");
public EchoServer() throws IOException {
this.selector = Selector.open();
this.serverSocketChannel = ServerSocketChannel.open();
this.serverSocketChannel.socket().setReuseAddress(true);
this.serverSocketChannel.configureBlocking(false);
this.serverSocketChannel.socket().bind(new InetSocketAddress(this.port));
System.out.println("服务器启动");
}
public void service() throws IOException {
this.serverSocketChannel.register(this.selector, SelectionKey.OP_ACCEPT);
while(this.selector.select() > 0) {
Set readyKeys = this.selector.selectedKeys();
Iterator it = readyKeys.iterator();
while(it.hasNext()) {
SelectionKey key = null;
try {
key = (SelectionKey)it.next();
it.remove();
if (key.isAcceptable()) {
ServerSocketChannel ssc = (ServerSocketChannel)key.channel();
SocketChannel socketChannel = ssc.accept();
PrintStream var10000 = System.out;
InetAddress var10001 = socketChannel.socket().getInetAddress();
var10000.println("接收到客户连接,来自:" + var10001 + ":" + socketChannel.socket().getPort());
socketChannel.configureBlocking(false);
ByteBuffer buffer = ByteBuffer.allocate(1024);
socketChannel.register(this.selector, 5, buffer);
}
if (key.isReadable()) {
this.receive(key);
}
if (key.isWritable()) {
this.send(key);
}
} catch (IOException var8) {
var8.printStackTrace();
try {
if (key != null) {
key.cancel();
key.channel().close();
}
} catch (Exception var7) {
var8.printStackTrace();
}
}
}
}
}
public void send(SelectionKey key) throws IOException {
ByteBuffer buffer = (ByteBuffer)key.attachment();
SocketChannel socketChannel = (SocketChannel)key.channel();
buffer.flip();
String data = this.decode(buffer);
if (data.indexOf("\r\n") != -1) {
String outputData = data.substring(0, data.indexOf("\n") + 1);
System.out.print(outputData);
ByteBuffer outputBuffer = this.encode("echo:" + outputData);
while(outputBuffer.hasRemaining()) {
socketChannel.write(outputBuffer);
}
ByteBuffer temp = this.encode(outputData);
buffer.position(temp.limit());
buffer.compact();
if (outputData.equals("bye\r\n")) {
key.cancel();
socketChannel.close();
System.out.println("关闭与客户的连接");
}
}
}
public void receive(SelectionKey key) throws IOException {
ByteBuffer buffer = (ByteBuffer)key.attachment();
SocketChannel socketChannel = (SocketChannel)key.channel();
ByteBuffer readBuff = ByteBuffer.allocate(32);
socketChannel.read(readBuff);
readBuff.flip();
buffer.limit(buffer.capacity());
buffer.put(readBuff);
}
public String decode(ByteBuffer buffer) {
CharBuffer charBuffer = this.charset.decode(buffer);
return charBuffer.toString();
}
public ByteBuffer encode(String str) {
return this.charset.encode(str);
}
public static void main(String[] args) throws Exception {
EchoServer server = new EchoServer();
server.service();
}
}
客户端
package com.mang.NIO.nsync;
import jdk.internal.util.xml.impl.Input;
import java.io.*;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.SocketChannel;
public class EchoClient {
private SocketChannel socketChannel = null;
public EchoClient() throws IOException {
socketChannel = SocketChannel.open();
InetAddress ia = InetAddress.getLocalHost();
InetSocketAddress isa = new InetSocketAddress(ia,8000);
socketChannel.connect(isa);
System.out.println("与服务器的连接建立成功");
}
public static void main(String[] args) throws IOException {
new EchoClient().talk();
}
private PrintWriter getWriter(Socket socket) throws IOException {
OutputStream socketOut = socket.getOutputStream();
return new PrintWriter(socketOut,true);
}
private BufferedReader getReader(Socket socket) throws IOException {
InputStream socketIn = socket.getInputStream();
return new BufferedReader(new InputStreamReader(socketIn));
}
public void talk() {
try {
BufferedReader br = getReader(socketChannel.socket());
PrintWriter pw = getWriter(socketChannel.socket());
BufferedReader localReader = new BufferedReader(new InputStreamReader(System.in));
String msg = null;
while((msg=localReader.readLine())!=null){
pw.println(msg);
System.out.println(br.readLine());
if(msg.equals("bye")) {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socketChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}