1.服务端
代码语言:javascript复制package d02_test;
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;
import java.util.Set;
/**
* zt
* 2020/8/11
* 18:02
*/
public class Server {
public static void main(String[] args) {
//1.创建ServerSockChannel
ServerSocketChannel listener = null;
try {
listener = ServerSocketChannel.open();
//2.绑定地址
listener.bind(new InetSocketAddress("10.0.139.160",10086));
//3.设置非阻塞模式
listener.configureBlocking(false);
//4.创建selector选择器
Selector selector = Selector.open();
//5.把通道注册到选择器,并指定注册事件
listener.register(selector, SelectionKey.OP_ACCEPT);
//6.轮询(Select()阻塞方法。没有事件发送阻塞)
System.out.println("服务器启动.....0.0");
while (selector.select()>0){
//7.处理
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext()){
SelectionKey selectionKey = iterator.next();
if(selectionKey.isAcceptable()){
SocketChannel socketChannel = listener.accept();
System.out.println(socketChannel.getRemoteAddress() "进入聊天室");
//设置非阻塞式模式
socketChannel.configureBlocking(false);
//注册到selector
socketChannel.register(selector, SelectionKey.OP_READ);
}else if(selectionKey.isReadable()){
//读取数据
SocketChannel channel = (SocketChannel) selectionKey.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
int len = 0;
//不会阻塞
try {
while ((len=channel.read(buffer))>0){
buffer.flip();
String data = new String(buffer.array(),0,buffer.limit());
System.out.println(channel.getRemoteAddress() "说:" data);
buffer.clear();
}
//开启线程回复
if(len==1){
System.out.println(channel.getRemoteAddress() "退出 了");
channel.close();
}
} catch (IOException e) {
System.out.println(channel.getRemoteAddress() "异常退出了");
channel.close();
}
}
//已经处理过了键删除掉
iterator.remove();
}
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
listener.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2.客户端
代码语言:javascript复制package d02_test;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;
/**
* zt
* 2020/8/11
* 18:02
*/
public class Client {
public static void main(String[] args) throws Exception {
//1.创建socketchannel
SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("10.0.139.160",10086));
//2.设置为非阻塞模式
socketChannel.configureBlocking(false);
//3.控制台录入并写出
Scanner sc = new Scanner(System.in);
while (true){
String data = sc.next();
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.put(data.getBytes());
buffer.flip();
socketChannel.write(buffer);
buffer.clear();
if(data.equals("886")){
break;
}
}
//关闭
socketChannel.close();
}
}
3.运行结果:
Server
代码语言:javascript复制服务器启动.....0.0
/10.0.139.160:60397进入聊天室
/10.0.139.160:60397说:呱?
/10.0.139.160:60397说:你好啊
Client
代码语言:javascript复制呱?
你好啊