服务端
package com.imikasa.demo7;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
/**
* target: NIO非阻塞通信入门demo server端
*/
public class Server {
public static void main(String[] args) throws IOException {
System.out.println("=========服务端启动==========");
//获取管道
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
//设置为非阻塞
serverSocketChannel.configureBlocking(false);
//绑定服务器端口
serverSocketChannel.bind(new InetSocketAddress(9999));
//获取选择器
Selector selector = Selector.open();
//将管道注册到选择器内
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
//(轮询)接收到事件
while(selector.select()>0){
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
//遍历事件迭代器
while(iterator.hasNext()){
SelectionKey selectionKey = iterator.next();
if(selectionKey.isAcceptable()){
//获取连接本服务端的客户端通道
SocketChannel socketChannel = serverSocketChannel.accept();
//设置为非阻塞
socketChannel.configureBlocking(false);
socketChannel.register(selector,SelectionKey.OP_READ);
}else if(selectionKey.isReadable()){
SocketChannel channel = (SocketChannel) selectionKey.channel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
int len;
while((len = channel.read(byteBuffer))>0){
byteBuffer.flip();
System.out.println("客户端发送的信息:"+new String(byteBuffer.array(),0,len));
byteBuffer.clear();
}
}
iterator.remove();
}
}
}
}
客户端
package com.imikasa.demo7;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.text.SimpleDateFormat;
import java.util.Scanner;
/**
* NIO非阻塞模式通信入门demo client端
*/
public class Client {
public static void main(String[] args) throws IOException {
System.out.println("请输入昵称:");
Scanner scanner = new Scanner(System.in);
String nikeName = scanner.nextLine();
//获取客户端通道,并且连接服务端
SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9999));
//设置非阻塞模式
socketChannel.configureBlocking(false);
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
while(true){
System.out.println("请对服务器说:");
String msg = scanner.nextLine();
byteBuffer.put((new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(System.currentTimeMillis())+"\t"+nikeName+":"+msg).getBytes());
byteBuffer.flip();
socketChannel.write(byteBuffer);
byteBuffer.clear();
}
}
}
网友评论