客户端流程
image.png
package com.example.demo;
public class TimeService {
public static void main(String[] args) {
int port =8080;
if(args !=null&& args.length>0){
try {
port=Integer.valueOf(args[0]);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
MultiplexerTimeService a =new MultiplexerTimeService(8080);
}
}
package com.example.demo;
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.Date;
import java.util.Iterator;
import java.util.Set;
public class MultiplexerTimeService implements Runnable {
private Selector selector;
private ServerSocketChannel servChannel;
private volatile boolean stop;
/**
* 初始化多路复用器
*
* @param port
*/
public MultiplexerTimeService(int port) {
try {
selector = Selector.open();
servChannel = ServerSocketChannel.open();
servChannel.configureBlocking(false);//
servChannel.socket().bind(new InetSocketAddress(port), 1024);
servChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("server已经启动");
} catch (IOException e) {
e.printStackTrace();
}
}
public void stop() {
this.stop = true;
}
private void handleInput(SelectionKey key) throws IOException {
if (key.isValid()) {
if (key.isAcceptable()) {
ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
SocketChannel sc = ssc.accept();
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_ACCEPT);
}
if (key.isReadable()) {
SocketChannel sc = (SocketChannel) key.channel();
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
int read = sc.read(readBuffer);
if (read > 0) {
readBuffer.flip();
byte[] bytes = new byte[readBuffer.remaining()];
readBuffer.get(bytes);
String body = new String(bytes, "utf-8");
String response = new Date().toString();
byte[] bytes1 = response.getBytes();
ByteBuffer allocate = ByteBuffer.allocate(bytes1.length);
allocate.put(bytes1);
allocate.flip();
sc.write(allocate);
} else if (read < 0) {
key.channel();
sc.close();
}
}
}
}
@Override
public void run() {
while (!stop) {
SelectionKey key = null;
try {
selector.select(1000);
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> it = selectionKeys.iterator();
while (it.hasNext()) {
key = it.next();
it.remove();
handleInput(key);
}
} catch (IOException e) {
if (key != null) {
key.cancel();
if (key.channel() != null) {
try {
key.channel().close();
} catch (IOException ex) {
ex.printStackTrace();
}
e.printStackTrace();
}
}
}
if (selector != null) {
try {
selector.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
网友评论