服務端
~~~
import java.io.*;
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 Server {
public static void main(String[] args) throws IOException {
// 服務端通道
final ServerSocketChannel ssChannel = ServerSocketChannel.open();
// 配置阻塞為false
ssChannel.configureBlocking(false);
// 綁定端口
ssChannel.bind(new InetSocketAddress(9999));
final Selector selector = Selector.open();
// 將通道都注冊到選擇器上,并且開始監聽事件
ssChannel.register(selector, SelectionKey.OP_ACCEPT);
// 使用Selector選擇器已經準備好的事件
while (selector.select()>0){
// 獲取選擇器中所有注冊的通道已經就緒好的事件
final Iterator<SelectionKey> iterator = selector
.selectedKeys()
.iterator();
while (iterator.hasNext()){
final SelectionKey selectionKey = iterator.next();
if (selectionKey.isAcceptable()){
final SocketChannel accept = ssChannel.accept();
accept.configureBlocking(false);
// 讀
accept.register(selector,SelectionKey.OP_READ);
}
// 讀
if (selectionKey.isReadable()){
final SocketChannel channel =(SocketChannel) selectionKey.channel();
final ByteBuffer allocate = ByteBuffer.allocate(1024);
int len=0;
while ((len=channel.read(allocate))>0){
allocate.flip();
System.out.println(new String(allocate.array(),0,len));
allocate.clear();
}
}
iterator.remove();
}
}
}
}
~~~
客戶端
~~~
import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws IOException {
final SocketChannel open = SocketChannel.open(new InetSocketAddress(9999));
open.configureBlocking(false);
final ByteBuffer allocate = ByteBuffer.allocate(1024);
final Scanner scanner = new Scanner(System.in);
while (true){
System.out.println("請說話:");
final String line = scanner.nextLine();
allocate.put(line.getBytes());
allocate.flip();
open.write(allocate);
allocate.clear();
}
}
}
~~~