}
NIO服务器处理请求类
package com.ruider.customerNIO;
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;
/**
- Created by mahede on 2018/11/20.
*/
public class NIOServerHandle implements Runnable{
private int port;
private ServerSocketChannel serverSocketChannel;
private Selector selector;
private volatile boolean start;
public NIOServerHandle(int port) {
this.port = port;
try {
selector = Selector.open();
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().bind(new InetSocketAddress(port), 1024);
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
start = true;
System.out.println(“NIOServer启动服务,端口:” + port);
}catch (Exception e) {
System.out.println(“封装NIO服务失败”);
System.out.println(e);
}
}
@Override
public void run(){
while(start) {
try{
//没1秒唤醒一次,轮询一遍事件
selector.select(1000);
Set selectionKeys = selector.selectedKeys();
Iterator it = selectionKeys.iterator();
SelectionKey selectionKey = null;
while(it.hasNext()) {
selectionKey = it.next();
it.remove();
try{
handleInput(selectionKey);
}catch(Exception e){
System.out.println(“服务获取信息失败”);
System.out.println(e);
}
}
}
catch (Exception e) {
System.out.println(e);
}
}
if(selector != null)
try{
selector.close();
}catch (Exception e) {
e.printStackTrace();
}
}
public void stop() { start = false;}
private void handleInput(SelectionKey key) throws Exception{
if(key.isValid()) {
if(key.isAcceptable()) {
ServerSocketChannel channel = (ServerSocketChannel) key.channel();
SocketChannel socketChannel = channel.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
}
if(key.isReadable()) {
SocketChannel socketChannel = (SocketChannel)key.channel();
//分配1M的buffer
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
int size = socketChannel.read(byteBuffer);
if(size > 0) {
//将缓冲区当前的limit设置为position=0,用于后续对缓冲区的读取操作
byteBuffer.flip();
byte[] bytes = new byte[byteBuffer.remaining()];
//复制到bytes中
byteBuffer.get(bytes);
String contents = new String(bytes, “UTF-8”);
System.out.println(“NIO服务收到消息:”+contents);
String expression = new String(bytes,“UTF-8”);
System.out.println(“服务器收到消息:” + expression);
doWrite(socketChannel, “收到信息,你好,我是NIO”);
}
else if(size < 0) {
key.cancel();
socketChannel.close();
}
}
}
}
private void doWrite(SocketChannel channel, String msg) {
try {
byte[] bytes = msg.getBytes();
ByteBuffer writebuffer = ByteBuffer.allocate(bytes.length);
writebuffer.put(bytes);
//postion,limit值的交换,用于输出buffer
writebuffer.flip();
channel.write(writebuffer);
}catch (Exception e) {
System.out.print(“[error]: NIOserver发送信息失败”);
e.printStackTrace();
}
}
}
NIO 客户端代码
提示
-
类Client用于启动NIO客户端,传输参数只有IP、PORT
-
类ClientHandle用于NIO客户端请求服务端以及处理服务端的数返回数据
NIO客户端启动类
package com.ruider.customerNIO;
/**
- Created by mahede on 2018/11/21.
*/
public class Client {
private static final String IP_ADDRESS = “localhost”;
private static final int PORT = 1234;
private static ClientHandle clientHandle;
public static void start(){ start(IP_ADDRESS, PORT);}
private synchronized static void start(String host, int port) {
if(clientHandle != null) {
clientHandle.stop();
}
clientHandle = new ClientHandle(IP_ADDRESS, PORT);
new Thread(clientHandle, “Client”).start();
}
//向服务器发送消息
public static boolean sendMsg(String msg) throws Exception{
if(msg.equals(“q”)) return false;
clientHandle.sendMsg(msg);
return true;
}
}
客户端发送请求和处理返回数据类
package com.ruider.customerNIO;
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;
/**
- Created by mahede on 2018/11/21.
*/
public class ClientHandle implements Runnable {
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数Java工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,真正体系化!
由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新
如果你觉得这些内容对你有帮助,可以添加V获取:vip1024b (备注Java)
最后
终极手撕架构师的学习笔记:分布式+微服务+开源框架+性能优化
img-rrI5sscz-1711638785318)]
[外链图片转存中…(img-RCd7jTYv-1711638785319)]
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,真正体系化!
由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新
如果你觉得这些内容对你有帮助,可以添加V获取:vip1024b (备注Java)
[外链图片转存中…(img-rrrUQFQ8-1711638785319)]
最后
终极手撕架构师的学习笔记:分布式+微服务+开源框架+性能优化
[外链图片转存中…(img-8Yu1N9Mt-1711638785319)]