确定目标:
客户端服务搭建
服务端服务搭建
Nio 中的必要知识点 Selector,Channel,ByteBuffer
Selector 可以绑定多个Channel ;
Channel内部都有一个Socke套接字(SocketChannel,ServerSocketChannel)
ByteBuffer用于数据载体。
客户端:
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.Set;
public class MyClient {
private int prot = 18080;
private final static String host = "127.0.0.1";
private Selector selector;
private SocketChannel socketChannel;
public MyClient() {
try{
this.selector = Selector.open();
InetSocketAddress inetSocketAddress = new InetSocketAddress(host, prot);
socketChannel = SocketChannel.open(inetSocketAddress);
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
String s = socketChannel.getLocalAddress().toString();
System.out.println(s+"连接");
}catch (Exception e){
e.printStackTrace();
}
}
public void handleMessage(){
try{
int select = selector.select();
if (select>0){
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
if (key.isAcceptable()){
}
if (key.isReadable()){
SocketChannel channel = (SocketChannel)key.channel();
ByteBuffer allocate = ByteBuffer.allocate(1024);
int read = channel.read(allocate);
if(read>0){
byte[] array = allocate.array();
System.out.println(new String(array));
}else if(read ==-1){
channel.close();
}else {
allocate.flip();
}
}
if(key.isWritable()){
// System.out.println("测试数据");
}
}
}
}catch (Exception e){
}
}
public void sendMessage(String message) throws IOException {
ByteBuffer wrap = ByteBuffer.wrap(message.getBytes());
socketChannel.write(wrap);
wrap.clear();
}
}
服务器端:
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;
import java.util.stream.Collectors;
public class MyServer {
private Selector selector;
private static final int prot = 18080;
private ServerSocketChannel serverSocketChannel;
public MyServer() {
try {
selector = Selector.open();
serverSocketChannel = ServerSocketChannel.open();
//绑定端口
serverSocketChannel.socket().bind(new InetSocketAddress(prot));
//设置为非阻塞
serverSocketChannel.configureBlocking(false);
//channel 和selector绑定
//SelectionKey.OP_ACCEPT 连接触发 SelectionKey的四种模式
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
} catch (Exception e) {
e.printStackTrace();
}
}
public void handleClient() {
try {
//存在事件要处理,存在channel通道要处理
int select = selector.select();
while (select > 0) {
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext()) {
SelectionKey next = iterator.next();
//监听到accep 连接事件
if (next.isAcceptable()) {
SocketChannel accept = ((ServerSocketChannel) next.channel()).accept();
accept.configureBlocking(false);
accept.register(selector, SelectionKey.OP_READ);
//提醒
ByteBuffer allocate = ByteBuffer.allocate(1024);
allocate.put((accept.getRemoteAddress() + "上线").getBytes());
sendMessageOtherClient(selector, next, allocate);
}
//可读
if (next.isReadable()) {
//处理读 (读取客户端数据)
//1 拿取到关联的客户端channel
SocketChannel accept = (SocketChannel) next.channel();
ByteBuffer allocate = ByteBuffer.allocate(1024);
byte[] bytes = (accept.getRemoteAddress() + "说:").getBytes();
allocate.put(bytes);
int read = accept.read(allocate);
//大于0存在数据
if (read > 0) {
sendMessageOtherClient(selector, next, allocate);
} else if (read == -1) {//数据读取完毕
accept.close();
} else {
allocate.flip();
}
}
//可写
if (next.isWritable()) {
//处理写
System.out.println("服务端测试数据");
}
selector.wakeup();
iterator.remove();//防止同一个SelectionKey重复处理
}
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void sendMessageOtherClient(Selector select, SelectionKey next, ByteBuffer message) throws IOException {
//select.keys(); 获取与select进行绑定的SelectionKey
//selector.selectedKeys(); 获取的是存在动作的正在执行活动的SelectionKey
Set<SelectionKey> selectionKeys = select.keys();
Set<SelectionKey> selectionKeysOther = selectionKeys.stream().filter(selectionKey -> !selectionKey.equals(next)).collect(Collectors.toSet());
Iterator<SelectionKey> iterator = selectionKeysOther.iterator();
while (iterator.hasNext()) {
SelectionKey next1 = iterator.next();
SelectableChannel channel1 = next1.channel();
if (channel1 instanceof SocketChannel) {
SocketChannel channel = (SocketChannel) channel1;
message.flip();//不进行flip操作,可能会导致无法写入数据
System.out.println(new String(message.array()));
channel.write(message);
}
}
message.clear();
}
}
客户端测试代码:
public static void main(String[] args) {
MyServer myServer = new MyServer();
new Thread(){
@Override
public void run() {
while (true){
myServer.handleClient();
}
}
}.start();
}
服务端测试代码:
public static void main(String[] args) {
MyClient myClient = new MyClient();
new Thread(){
@Override
public void run() {
while (true){
myClient.handleMessage();
try{
Thread.currentThread().sleep(3000);
}catch (Exception e){
}
}
}
}.start();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()){
String s = scanner.nextLine();
try {
myClient.sendMessage(s);
} catch (IOException e) {
e.printStackTrace();
}
}
}