Commit 7561cc8b647006fe4637ea8bd91f9699be363e8e

Authored by 杜云山
1 parent 75092d17

feat: 完成一个

feat: 完成一个
src/main/java/com/example/mina/base/AbstractVirtualBoxHandler.java 0 → 100644
@@ -0,0 +1,32 @@ @@ -0,0 +1,32 @@
  1 +package com.example.mina.base;
  2 +
  3 +import org.apache.mina.core.service.IoHandlerAdapter;
  4 +
  5 +/**
  6 + * @author 杜云山
  7 + * @date 21/03/05
  8 + */
  9 +public abstract class AbstractVirtualBoxHandler extends IoHandlerAdapter {
  10 +
  11 + /**
  12 + * 存储衰减值的矩阵
  13 + */
  14 + protected int[][] matrix;
  15 +
  16 + protected int type;
  17 +
  18 + protected int row = 10;
  19 +
  20 + protected int maxAttenuate = 99;
  21 +
  22 + /**
  23 + * 初始化矩阵以及该设备的一些参数
  24 + */
  25 + protected abstract void initMatrix();
  26 +
  27 + /**
  28 + * 处理消息
  29 + */
  30 + protected abstract void handleMessage();
  31 +
  32 +}
src/main/java/com/example/mina/base/AeroflexDataBuffer.java 0 → 100644
@@ -0,0 +1,27 @@ @@ -0,0 +1,27 @@
  1 +package com.example.mina.base;
  2 +
  3 +/**
  4 + * @author 杜云山
  5 + * @date 2021/03/05
  6 + */
  7 +public class AeroflexDataBuffer extends HardwareDataBuffer {
  8 +
  9 + public AeroflexDataBuffer(int row, int maxAtten) {
  10 + super(row, row, row, maxAtten);
  11 +
  12 + matrix_data = new Entry[row][row];
  13 + offset_data = new Entry[row];
  14 +
  15 + for (int i = 0; i < row; i++) {
  16 + for (int k = 0; k < row; k++) {
  17 + matrix_data[i][k] = new Entry(i, k, "kk", maxAtten, false);
  18 + }
  19 + }
  20 +
  21 + for (int i = 0; i < row; i++) {
  22 + offset_data[i] = new Entry(i, 0, "rr", maxAtten, false);
  23 + }
  24 +
  25 + }
  26 +
  27 +}
src/main/java/com/example/mina/base/Entry.java 0 → 100644
@@ -0,0 +1,60 @@ @@ -0,0 +1,60 @@
  1 +package com.example.mina.base;
  2 +
  3 +/**
  4 + * @author 杜云山
  5 + * @date 2021/03/05
  6 + */
  7 +public class Entry {
  8 +
  9 + private final int row;
  10 +
  11 + private final int col;
  12 +
  13 + private final String name;
  14 +
  15 + private int value;
  16 +
  17 + private final boolean booked;
  18 +
  19 + private final long timestamp;
  20 +
  21 + public static final Entry EMPTY = new Entry(0, 0, null, 0, false);
  22 +
  23 + public Entry(int row, int col, String name, int value, boolean booked) {
  24 + this.row = row;
  25 + this.col = col;
  26 + this.name = name;
  27 + this.value = value;
  28 + this.booked = booked;
  29 + this.timestamp = System.nanoTime();
  30 + }
  31 +
  32 + public int getRow() {
  33 + return row;
  34 + }
  35 +
  36 + public int getCol() {
  37 + return col;
  38 + }
  39 +
  40 + public String getName() {
  41 + return name;
  42 + }
  43 +
  44 + public int getValue() {
  45 + return value;
  46 + }
  47 +
  48 + public boolean isBooked() {
  49 + return booked;
  50 + }
  51 +
  52 + public void setValue(int v) {
  53 + this.value = v;
  54 + }
  55 +
  56 + public long getTimestamp() {
  57 + return this.timestamp;
  58 + }
  59 +
  60 +}
src/main/java/com/example/mina/base/HardwareDataBuffer.java 0 → 100644
@@ -0,0 +1,86 @@ @@ -0,0 +1,86 @@
  1 +package com.example.mina.base;
  2 +
  3 +public class HardwareDataBuffer {
  4 +
  5 + protected int maxRow;
  6 + protected int maxCol;
  7 + protected int maxOffset;
  8 +
  9 + protected int maxAtten;
  10 +
  11 +
  12 + protected Entry[][] matrix_data;
  13 + protected Entry[] offset_data;
  14 +
  15 + public HardwareDataBuffer() {}
  16 +
  17 + public HardwareDataBuffer(int row, int col, int offset, int maxAtten){
  18 + this.maxRow = row;
  19 + this.maxCol = col;
  20 + this.maxOffset = offset;
  21 + this.maxAtten = maxAtten;
  22 + }
  23 +
  24 +
  25 + /**
  26 + * Set cross point attenuation value. Actually that is not correct.
  27 + * In case of LTE device, this is a ON/OFF status (0,1)
  28 + *
  29 + * @param row the row index. *** starts from 1 ***
  30 + * @param col the col index. *** starts from 1 ***
  31 + * @param val the attenuation value
  32 + */
  33 + public synchronized void setAttenuation(int row, int col, int val){
  34 +
  35 + if(val != -1 && (row < 1 || row > maxRow || col < 1 || col > maxCol)) {
  36 + //Logger.atError().log("HardwareDataBuffer: setAttenuation(int row, int col, int val) " + row + "/" + col + "/" + val);
  37 + return;
  38 + }
  39 + if(val == -1) val = maxAtten;
  40 + matrix_data[row - 1][col -1 ] = new Entry(row -1 , col -1 , "rr", val, false);;
  41 + }
  42 +
  43 +
  44 + public int getAttenuation(int row, int col){
  45 + return matrix_data[row - 1][col -1 ].getValue();
  46 + }
  47 +
  48 + public synchronized void setOffset(int row,int val){
  49 + if(row < 1 || row > maxOffset){
  50 + //rfmazeLogger.atError().log("HardwareDataBuffer: setOffset(int row, int val) " + row + "/" + val);
  51 + return;
  52 + }
  53 + offset_data[row - 1] = new Entry(row -1 , 0 , "rr", val, false);;
  54 + }
  55 +
  56 + public int getOffset(int row){
  57 + return offset_data[row - 1].getValue();
  58 + }
  59 +
  60 +
  61 + public Entry[] getOffset_data() {
  62 + return offset_data;
  63 + }
  64 +
  65 + public Entry[][] getMatrix_data() {
  66 + return matrix_data;
  67 + }
  68 +
  69 + public int getMaxRow(){
  70 + return maxRow;
  71 + }
  72 +
  73 + public int getMaxCol(){
  74 + return maxCol;
  75 + }
  76 +
  77 + public int getMaxOffset() {
  78 + return maxOffset;
  79 + }
  80 +
  81 + public int getMaxAtten() {
  82 + return maxAtten;
  83 + }
  84 +
  85 +
  86 +}
src/main/java/com/example/mina/box1/Box1Decoder.java 0 → 100644
@@ -0,0 +1,9 @@ @@ -0,0 +1,9 @@
  1 +package com.example.mina.box1;
  2 +
  3 +/**
  4 + * @author 杜云山
  5 + * @date 21/03/05
  6 + */
  7 +public class Box1Decoder {
  8 +
  9 +}
src/main/java/com/example/mina/box1/Box1Encoder.java 0 → 100644
@@ -0,0 +1,9 @@ @@ -0,0 +1,9 @@
  1 +package com.example.mina.box1;
  2 +
  3 +/**
  4 + * @author 杜云山
  5 + * @date 21/03/05
  6 + */
  7 +public class Box1Encoder {
  8 +
  9 +}
src/main/java/com/example/mina/box1/Box1Handler.java 0 → 100644
@@ -0,0 +1,139 @@ @@ -0,0 +1,139 @@
  1 +package com.example.mina.box1;
  2 +
  3 +import com.example.mina.base.AbstractVirtualBoxHandler;
  4 +import com.example.mina.base.AeroflexDataBuffer;
  5 +import com.example.mina.util.StrUtil;
  6 +import lombok.extern.slf4j.Slf4j;
  7 +import org.apache.mina.core.buffer.IoBuffer;
  8 +import org.apache.mina.core.session.IoSession;
  9 +
  10 +/**
  11 + * @author 杜云山
  12 + * @date 21/03/05
  13 + */
  14 +@Slf4j
  15 +public class Box1Handler extends AbstractVirtualBoxHandler {
  16 +
  17 +
  18 + private static final byte[] ERROR = "ERROR".getBytes();
  19 +
  20 + private static final byte[] NONE = "OK".getBytes();
  21 +
  22 + private AeroflexDataBuffer dataBuffer;
  23 +
  24 + public Box1Handler() {
  25 + this.initMatrix();
  26 + }
  27 +
  28 + @Override
  29 + protected void initMatrix() {
  30 +
  31 + int row = 10;
  32 + int col = 1;
  33 + int maxAtten = 888;
  34 +
  35 + dataBuffer = new AeroflexDataBuffer(row, maxAtten);
  36 + }
  37 +
  38 + @Override
  39 + protected void handleMessage() {
  40 +
  41 + }
  42 +
  43 + @Override
  44 + public void messageReceived(IoSession session, Object message) {
  45 +
  46 + IoBuffer ioBuffer = (IoBuffer) message;
  47 + byte[] bytes = new byte[ioBuffer.limit()];
  48 + ioBuffer.get(bytes, ioBuffer.position(), ioBuffer.limit());
  49 +
  50 + byte[] result = handleCommand(bytes, bytes.length);
  51 +
  52 + session.write(IoBuffer.wrap(result));
  53 + }
  54 +
  55 + @Override
  56 + public void sessionCreated(IoSession session) {
  57 +
  58 + log.info("---server session created");
  59 + }
  60 +
  61 + @Override
  62 + public void sessionOpened(IoSession session) {
  63 +
  64 + log.info("---server session Opened");
  65 + }
  66 +
  67 + @Override
  68 + public void sessionClosed(IoSession session) {
  69 +
  70 + log.info("---server session Closed");
  71 + }
  72 +
  73 + @Override
  74 + public void messageSent(IoSession session, Object message) {
  75 +
  76 + log.info("---发送数据成功了。。。{}", message);
  77 + }
  78 +
  79 +
  80 + protected byte[] handleCommand(byte[] cmd, int len) {
  81 + String command = new String(cmd).trim();
  82 +
  83 +// LogUtils.println("AeroflexVirtualBoxService::handleCommand receive : ", command);
  84 +
  85 + if (command.startsWith("ATTN ALL MAX")) {//set all to max
  86 + for (int i = 1; i < dataBuffer.getMaxRow(); i++) {
  87 + dataBuffer.setOffset(i, dataBuffer.getMaxAtten());
  88 + }
  89 +
  90 + return NONE;
  91 + } else if (command.startsWith("ATTN?")) {//get
  92 + String[] sss = command.split(" ");
  93 + if (sss.length >= 2) {
  94 +// LogUtils.println(sss[0], sss[1]);
  95 +
  96 + int row = StrUtil.toInt(sss[1]);
  97 + if (row >= 0 && row <= dataBuffer.getMaxRow()) {
  98 + String str = String.valueOf(dataBuffer.getOffset(row));
  99 +// LogUtils.println("AeroflexVirtualBoxService::handleCommand return : ", str);
  100 + return str.getBytes();
  101 + }
  102 + }
  103 +
  104 + return ERROR;
  105 + } else if (command.startsWith("ATTN")) {//Set, Follow by ATTN?
  106 +// LogUtils.println("command.startsWith(\"ATTN\")");
  107 + String[] aa = command.split(";");
  108 +
  109 +// LogUtils.println(aa[0], aa[1]);
  110 +
  111 + String[] sss = aa[0].split(" ");
  112 + StrUtil.printArray(sss);
  113 +
  114 + if (sss.length >= 3) {
  115 + int row = StrUtil.toInt(sss[1]);
  116 + int val = StrUtil.toInt(sss[2]);
  117 +
  118 + System.out.println(row + "/" + val);
  119 +
  120 + if (row >= 0 && row <= dataBuffer.getMaxRow()) {
  121 + if (val >= 0 && val <= dataBuffer.getMaxAtten()) {
  122 + dataBuffer.setOffset(row, val);
  123 +
  124 + String str = String.valueOf(dataBuffer.getOffset(row));
  125 +// LogUtils.println("handleCommand return =====> ", str);
  126 + return str.getBytes();
  127 + }
  128 + }
  129 + }
  130 +
  131 + return ERROR;
  132 +
  133 + } else {
  134 + return ERROR;
  135 + }
  136 +
  137 + }
  138 +
  139 +}
src/main/java/com/example/mina/config/Box1Configuration.java 0 → 100644
@@ -0,0 +1,48 @@ @@ -0,0 +1,48 @@
  1 +package com.example.mina.config;
  2 +
  3 +import com.example.mina.box1.Box1Handler;
  4 +import lombok.extern.slf4j.Slf4j;
  5 +import org.apache.mina.core.service.IoAcceptor;
  6 +import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
  7 +import org.springframework.context.annotation.Bean;
  8 +import org.springframework.context.annotation.Configuration;
  9 +
  10 +import java.io.IOException;
  11 +import java.net.InetSocketAddress;
  12 +
  13 +/**
  14 + * @author 杜云山
  15 + * @date 21/03/05
  16 + */
  17 +@Slf4j
  18 +@Configuration
  19 +public class Box1Configuration {
  20 +
  21 + /**
  22 + * 开启mina的server服务
  23 + */
  24 + @Bean
  25 + public IoAcceptor ioAcceptor() throws IOException {
  26 +
  27 + NioSocketAcceptor acceptor = new NioSocketAcceptor();
  28 + acceptor.setHandler(new Box1Handler());
  29 + acceptor.setReuseAddress(true);
  30 + acceptor.bind(new InetSocketAddress(9090));
  31 +
  32 + return acceptor;
  33 +
  34 + }
  35 +
  36 + @Bean
  37 + public IoAcceptor ioAcceptor999() throws IOException {
  38 +
  39 + NioSocketAcceptor acceptor = new NioSocketAcceptor();
  40 + acceptor.setHandler(new Box1Handler());
  41 + acceptor.setReuseAddress(true);
  42 + acceptor.bind(new InetSocketAddress(9999));
  43 +
  44 + return acceptor;
  45 +
  46 + }
  47 +
  48 +}
src/main/java/com/example/mina/config/Box2Configuration.java 0 → 100644
@@ -0,0 +1,9 @@ @@ -0,0 +1,9 @@
  1 +package com.example.mina.config;
  2 +
  3 +/**
  4 + * @author 杜云山
  5 + * @date 21/03/05
  6 + */
  7 +public class Box2Configuration {
  8 +
  9 +}
src/main/java/com/example/mina/config/ConfigMina.java
@@ -1,97 +0,0 @@ @@ -1,97 +0,0 @@
1 -package com.example.mina.config;  
2 -  
3 -import com.example.mina.mina.code.ByteFactory;  
4 -import com.example.mina.mina.server.MinaServerHandler;  
5 -import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;  
6 -import org.apache.mina.core.service.IoAcceptor;  
7 -import org.apache.mina.core.session.IdleStatus;  
8 -import org.apache.mina.filter.codec.ProtocolCodecFilter;  
9 -import org.apache.mina.filter.executor.ExecutorFilter;  
10 -import org.apache.mina.filter.logging.LoggingFilter;  
11 -import org.apache.mina.transport.socket.nio.NioSocketAcceptor;  
12 -import org.springframework.context.annotation.Bean;  
13 -import org.springframework.context.annotation.Configuration;  
14 -  
15 -import java.io.IOException;  
16 -import java.net.InetSocketAddress;  
17 -  
18 -/**  
19 - * @author dy  
20 - * @date 2021/3/3  
21 - */  
22 -@Configuration  
23 -public class ConfigMina {  
24 -  
25 - /**  
26 - * 配置mina的多线程过滤器  
27 - *  
28 - * @return  
29 - */  
30 - @Bean  
31 - public ExecutorFilter executorFilter() {  
32 - //设置初始化线程数,最大线程数  
33 - ExecutorFilter executorFilter = new ExecutorFilter(10, 20);  
34 - return executorFilter;  
35 - }  
36 -  
37 - /**  
38 - * 配置mina的转码过滤器  
39 - *  
40 - * @return  
41 - */  
42 - @Bean  
43 - public ProtocolCodecFilter protocolCodecFilter() {  
44 -// TextLineCodecFactory factory = new TextLineCodecFactory(Charset.forName("UTF-8"),  
45 -// LineDelimiter.WINDOWS.getValue(), LineDelimiter.WINDOWS.getValue());  
46 -  
47 -  
48 - //TextLineCodecFactory factory = new TextLineCodecFactory(Charset.forName("UTF-8"), LineDelimiter.WINDOWS.getValue(), LineDelimiter.WINDOWS.getValue());  
49 - ProtocolCodecFilter pcf = new ProtocolCodecFilter(new ByteFactory());  
50 - //ProtocolCodecFilter pcf = new ProtocolCodecFilter(factory);  
51 - return pcf;  
52 - }  
53 -  
54 - /**  
55 - * 配置mina的日志过滤器  
56 - *  
57 - * @return  
58 - */  
59 - @Bean  
60 - public LoggingFilter loggingFilter() {  
61 - return new LoggingFilter();  
62 - }  
63 -  
64 - /**  
65 - * 将过滤器注入到mina的链式管理器中  
66 - *  
67 - * @return  
68 - */  
69 - @Bean  
70 - public DefaultIoFilterChainBuilder defaultIoFilterChainBuilder() {  
71 - DefaultIoFilterChainBuilder def = new DefaultIoFilterChainBuilder();  
72 - def.addLast("executor", executorFilter());  
73 - def.addLast("logger", loggingFilter());  
74 - def.addLast("protocol", protocolCodecFilter());  
75 - return def;  
76 - }  
77 -  
78 - /**  
79 - * 开启mina的server服务,并设置对应的参数  
80 - *  
81 - * @return  
82 - * @throws IOException  
83 - */  
84 - @Bean  
85 - public IoAcceptor ioAcceptor() throws IOException {  
86 - IoAcceptor nio = new NioSocketAcceptor();  
87 - //设置缓冲区大小  
88 - nio.getSessionConfig().setReadBufferSize(2048);  
89 - //设置空闲状态时间,10秒没操作就进入空闲状态  
90 - nio.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);  
91 - nio.setFilterChainBuilder(defaultIoFilterChainBuilder());  
92 - nio.setHandler(new MinaServerHandler());  
93 - nio.bind(new InetSocketAddress(9098));  
94 - return nio;  
95 - }  
96 -  
97 -}  
src/main/java/com/example/mina/config/SecurityConfig.java
@@ -1,27 +0,0 @@ @@ -1,27 +0,0 @@
1 -package com.example.mina.config;  
2 -  
3 -import org.springframework.context.annotation.Configuration;  
4 -import org.springframework.security.config.annotation.web.builders.HttpSecurity;  
5 -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;  
6 -  
7 -/**  
8 - * @author dy  
9 - * @date 2021/2/25  
10 - */  
11 -@Configuration  
12 -public class SecurityConfig extends WebSecurityConfigurerAdapter {  
13 -  
14 - @Override  
15 - protected void configure(HttpSecurity http) throws Exception {  
16 - // 首页所有人都可以访问,功能也只有对应有权限的人才能访问到  
17 - // 请求授权的规则  
18 -  
19 -// http.authorizeRequests()  
20 -// .antMatchers("/").permitAll()  
21 -// .antMatchers("/level1/**").hasRole("vip1")  
22 -// .antMatchers("/level2/**").hasRole("vip2")  
23 -// .antMatchers("/level3/**").hasRole("vip3");  
24 - // 开启自动配置的登录功能  
25 - http.formLogin();  
26 - }  
27 -}  
src/main/java/com/example/mina/controller/RouterController.java
@@ -1,41 +0,0 @@ @@ -1,41 +0,0 @@
1 -package com.example.mina.controller;  
2 -  
3 -import lombok.extern.slf4j.Slf4j;  
4 -import org.springframework.stereotype.Controller;  
5 -import org.springframework.web.bind.annotation.GetMapping;  
6 -import org.springframework.web.bind.annotation.PathVariable;  
7 -  
8 -/**  
9 - * @author dy  
10 - * @date 2021/2/22  
11 - */  
12 -@Controller  
13 -@Slf4j  
14 -public class RouterController {  
15 -  
16 - @GetMapping({"/", "/index"})  
17 - public String index() {  
18 - log.info("是否进入程序");  
19 - return "/index";  
20 - }  
21 -  
22 - @GetMapping("/toLogin")  
23 - public String toLogin() {  
24 - return "views/login";  
25 - }  
26 -  
27 - @GetMapping("/level1/{id}")  
28 - public String level1(@PathVariable("id") int id) {  
29 - return "views/level1/" + id;  
30 - }  
31 -  
32 - @GetMapping("/level2/{id}")  
33 - public String level2(@PathVariable("id") int id) {  
34 - return "views/level2/" + id;  
35 - }  
36 -  
37 - @GetMapping("/level3/{id}")  
38 - public String level3(@PathVariable("id") int id) {  
39 - return "views/level3/" + id;  
40 - }  
41 -}  
src/main/java/com/example/mina/entity/AttenuationVO.java 0 → 100644
@@ -0,0 +1,9 @@ @@ -0,0 +1,9 @@
  1 +package com.example.mina.entity;
  2 +
  3 +/**
  4 + * @author 杜云山
  5 + * @date 21/03/05
  6 + */
  7 +public class AttenuationVO {
  8 +
  9 +}
src/main/java/com/example/mina/entity/Message.java 0 → 100644
@@ -0,0 +1,9 @@ @@ -0,0 +1,9 @@
  1 +package com.example.mina.entity;
  2 +
  3 +/**
  4 + * @author 杜云山
  5 + * @date 21/03/05
  6 + */
  7 +public class Message {
  8 +
  9 +}
src/main/java/com/example/mina/http/HttpSimulator.java
@@ -1,136 +0,0 @@ @@ -1,136 +0,0 @@
1 -package com.example.mina.http;  
2 -  
3 -import java.io.*;  
4 -import java.net.InetSocketAddress;  
5 -import java.net.Socket;  
6 -  
7 -/**  
8 - * @author dy  
9 - * @date 2021/3/4  
10 - */  
11 -public class HttpSimulator {  
12 -  
13 - private Socket socket;  
14 -  
15 - private int port = 80;  
16 -  
17 - private String host = "localhost";  
18 -  
19 - private String request = ""; // HTTP请求消息  
20 -  
21 - private boolean isPost, isHead;  
22 -  
23 -  
24 - public void run() throws Exception {  
25 - BufferedReader reader = new BufferedReader(new InputStreamReader(  
26 - System.in));  
27 - while (true) // 开始大循环  
28 - {  
29 - try {  
30 - if (!readHostAndPort(reader)) {  
31 - break;  
32 - }  
33 - readHttpRequest(reader);  
34 - sendHttpRequest();  
35 - readHttpResponse(reader);  
36 -  
37 - } catch (Exception e) {  
38 - System.out.println("err:" + e.getMessage());  
39 -  
40 - }  
41 -  
42 - }  
43 -  
44 - }  
45 -  
46 -  
47 - public static void main(String[] args) throws Exception {  
48 - new HttpSimulator().run();  
49 -  
50 - }  
51 -  
52 - private boolean readHostAndPort(BufferedReader consoleReader)  
53 - throws Exception {  
54 - System.out.print("host:port>");  
55 - String[] ss = null;  
56 - String s = consoleReader.readLine();  
57 - if (s.equals("q")) {  
58 - return false;  
59 - } else {  
60 - ss = s.split("[:]");  
61 - if (!ss[0].equals("")) {  
62 - host = ss[0];  
63 - }  
64 - if (ss.length > 1) {  
65 - port = Integer.parseInt(ss[1]);  
66 - }  
67 - System.out.println(host + ":" + String.valueOf(port));  
68 - return true;  
69 - }  
70 - }  
71 -  
72 - private void readHttpRequest(BufferedReader consoleReader)  
73 - throws Exception {  
74 - System.out.println("请输入HTTP请求:");  
75 - String s = consoleReader.readLine();  
76 - request = s + "\r\n";  
77 - boolean isPost = s.substring(0, 4).equals("POST");  
78 - boolean isHead = s.substring(0, 4).equals("HEAD");  
79 - while (!(s = consoleReader.readLine()).equals("")) {  
80 - request = request + s + "\r\n";  
81 - }  
82 - request = request + "\r\n";  
83 - if (isPost) {  
84 - System.out.println("请输入POST方法的内容:");  
85 - s = consoleReader.readLine();  
86 - request = request + s;  
87 - }  
88 - }  
89 -  
90 - private void sendHttpRequest() throws Exception {  
91 - socket = new Socket();  
92 - socket.setSoTimeout(10 * 1000);  
93 - System.out.println("正在连接服务器");  
94 - socket.connect(new InetSocketAddress(host, port), 10 * 1000);  
95 - System.out.println("服务器连接成功!");  
96 - OutputStream out = socket.getOutputStream();  
97 - OutputStreamWriter writer = new OutputStreamWriter(out);  
98 - writer.write(request);  
99 - writer.flush();  
100 - }  
101 -  
102 - private void readHttpResponse(BufferedReader consoleReader) {  
103 - String s = "";  
104 - try {  
105 - InputStream in = socket.getInputStream();  
106 - InputStreamReader inReader = new InputStreamReader(in);  
107 - BufferedReader socketReader = new BufferedReader(inReader);  
108 - System.out.println("---------HTTP头---------");  
109 - boolean b = true; // true: 未读取消息头 false: 已经读取消息头  
110 - while ((s = socketReader.readLine()) != null) {  
111 - if (s.equals("") && b == true && !isHead) {  
112 - System.out.println("------------------------");  
113 - b = false;  
114 - System.out.print("是否显示HTTP的内容(Y/N):");  
115 - String choice = consoleReader.readLine();  
116 - if (choice.equals("Y") || choice.equals("y")) {  
117 - System.out.println("---------HTTP内容---------");  
118 - continue;  
119 - } else {  
120 - break;  
121 - }  
122 - } else {  
123 - System.out.println(s);  
124 - }  
125 - }  
126 - } catch (Exception e) {  
127 - System.out.println("err:" + e.getMessage());  
128 - } finally {  
129 - try {  
130 - socket.close();  
131 - } catch (Exception e) {  
132 - }  
133 - }  
134 - System.out.println("------------------------");  
135 - }  
136 -}  
src/main/java/com/example/mina/mina/client/MinaClient.java
@@ -1,40 +0,0 @@ @@ -1,40 +0,0 @@
1 -package com.example.mina.mina.client;  
2 -  
3 -import org.apache.mina.core.service.IoConnector;  
4 -import org.apache.mina.filter.codec.ProtocolCodecFilter;  
5 -import org.apache.mina.filter.codec.textline.LineDelimiter;  
6 -import org.apache.mina.filter.codec.textline.TextLineCodecFactory;  
7 -import org.apache.mina.transport.socket.nio.NioSocketConnector;  
8 -  
9 -import java.net.InetSocketAddress;  
10 -import java.nio.charset.Charset;  
11 -  
12 -/**  
13 - * @author dy  
14 - * @date 2021/3/3  
15 - */  
16 -public class MinaClient {  
17 -  
18 - public static void main(String[] args) {  
19 - //1、创建客户端IoService  
20 - IoConnector connector = new NioSocketConnector();  
21 - //客户端链接超时时间  
22 - connector.setConnectTimeoutMillis(30000);  
23 - //2、客户端过滤器  
24 - connector.getFilterChain().addLast("test",  
25 - new ProtocolCodecFilter(  
26 - new TextLineCodecFactory(  
27 - Charset.forName("UTF-8"),  
28 - LineDelimiter.WINDOWS.getValue(),  
29 - LineDelimiter.WINDOWS.getValue()  
30 - )  
31 - )  
32 - );  
33 - //3、客户端IoHandler,发生消息  
34 - connector.setHandler(new MinaClientHandler("2"));  
35 - //连接服务端  
36 - connector.connect(new InetSocketAddress("localhost", 9098));  
37 -  
38 - }  
39 -  
40 -}  
src/main/java/com/example/mina/mina/client/MinaClientHandler.java
@@ -1,39 +0,0 @@ @@ -1,39 +0,0 @@
1 -package com.example.mina.mina.client;  
2 -  
3 -import org.apache.mina.core.service.IoHandlerAdapter;  
4 -import org.apache.mina.core.session.IoSession;  
5 -  
6 -/**  
7 - * @author dy  
8 - * @date 2021/3/3  
9 - */  
10 -public class MinaClientHandler extends IoHandlerAdapter {  
11 -  
12 - private final String values;  
13 -  
14 - public MinaClientHandler(String values) {  
15 - this.values = values;  
16 - }  
17 -  
18 - @Override  
19 - public void sessionOpened(IoSession session) {  
20 - session.write(values);  
21 -// //调用IoService的dispose方法关闭线程,这样每次调用client方法发送数据之后就会关闭client  
22 -// IoService service = session.getService();  
23 -// service.dispose();  
24 -  
25 - }  
26 -  
27 - /**  
28 - * 接收服务器端反馈消息  
29 - *  
30 - * @param session  
31 - * @param message  
32 - * @throws Exception  
33 - */  
34 - @Override  
35 - public void messageReceived(IoSession session, Object message) throws Exception {  
36 - System.out.println("收到服务器响应消息:" + message);  
37 - }  
38 -  
39 -}  
src/main/java/com/example/mina/mina/code/ByteDecoder.java
@@ -1,29 +0,0 @@ @@ -1,29 +0,0 @@
1 -package com.example.mina.mina.code;  
2 -  
3 -import org.apache.mina.core.buffer.IoBuffer;  
4 -import org.apache.mina.core.session.IoSession;  
5 -import org.apache.mina.filter.codec.ProtocolDecoder;  
6 -import org.apache.mina.filter.codec.ProtocolDecoderAdapter;  
7 -import org.apache.mina.filter.codec.ProtocolDecoderOutput;  
8 -import org.slf4j.Logger;  
9 -import org.slf4j.LoggerFactory;  
10 -  
11 -/**  
12 - * @author dy  
13 - * @date 2021/3/3  
14 - */  
15 -public class ByteDecoder extends ProtocolDecoderAdapter {  
16 - //打印日志信息  
17 - private final static Logger log = LoggerFactory  
18 - .getLogger(ProtocolDecoder.class);  
19 -  
20 - @Override  
21 - public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {  
22 - int limit = in.limit();  
23 - byte[] bytes = new byte[limit];  
24 -  
25 - in.get(bytes);  
26 -  
27 - out.write(bytes);  
28 - }  
29 -}  
src/main/java/com/example/mina/mina/code/ByteEnCoder.java
@@ -1,37 +0,0 @@ @@ -1,37 +0,0 @@
1 -package com.example.mina.mina.code;  
2 -  
3 -import org.apache.mina.core.buffer.IoBuffer;  
4 -import org.apache.mina.core.session.IoSession;  
5 -import org.apache.mina.filter.codec.ProtocolEncoder;  
6 -import org.apache.mina.filter.codec.ProtocolEncoderAdapter;  
7 -import org.apache.mina.filter.codec.ProtocolEncoderOutput;  
8 -import org.slf4j.Logger;  
9 -import org.slf4j.LoggerFactory;  
10 -  
11 -/**  
12 - * @author dy  
13 - * @date 2021/3/3  
14 - */  
15 -public class ByteEnCoder extends ProtocolEncoderAdapter {  
16 - //用于打印日志信息  
17 - private final static Logger log = LoggerFactory  
18 - .getLogger(ProtocolEncoder.class);  
19 -  
20 - //编码 将数据包转成字节数组  
21 - @Override  
22 - public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {  
23 - byte[] bytes = (byte[]) message;  
24 -  
25 - IoBuffer buffer = IoBuffer.allocate(256);  
26 - buffer.setAutoExpand(true);  
27 -  
28 - buffer.put(bytes);  
29 - buffer.flip();  
30 -  
31 - out.write(buffer);  
32 - out.flush();  
33 -  
34 - buffer.free();  
35 - }  
36 -  
37 -}  
src/main/java/com/example/mina/mina/code/ByteFactory.java
@@ -1,34 +0,0 @@ @@ -1,34 +0,0 @@
1 -package com.example.mina.mina.code;  
2 -  
3 -import org.apache.mina.core.session.IoSession;  
4 -import org.apache.mina.filter.codec.ProtocolCodecFactory;  
5 -import org.apache.mina.filter.codec.ProtocolDecoder;  
6 -import org.apache.mina.filter.codec.ProtocolEncoder;  
7 -  
8 -/**  
9 - * @author dy  
10 - * @date 2021/3/3  
11 - */  
12 -public class ByteFactory implements ProtocolCodecFactory {  
13 - private final ByteDecoder decoder;  
14 - private final ByteEnCoder encoder;  
15 -  
16 - //构造  
17 - public ByteFactory() {  
18 - encoder = new ByteEnCoder();  
19 - decoder = new ByteDecoder();  
20 - }  
21 -  
22 - @Override  
23 - public ProtocolDecoder getDecoder(IoSession arg0) throws Exception {  
24 - // TODO Auto-generated method stub  
25 - return decoder;  
26 - }  
27 -  
28 - @Override  
29 - public ProtocolEncoder getEncoder(IoSession arg0) throws Exception {  
30 - // TODO Auto-generated method stub  
31 - return encoder;  
32 - }  
33 -  
34 -}  
src/main/java/com/example/mina/mina/server/MinaServer.java
@@ -1,92 +0,0 @@ @@ -1,92 +0,0 @@
1 -package com.example.mina.mina.server;  
2 -  
3 -import com.example.mina.mina.code.ByteFactory;  
4 -import org.apache.mina.core.service.IoAcceptor;  
5 -import org.apache.mina.core.session.IdleStatus;  
6 -import org.apache.mina.filter.codec.ProtocolCodecFilter;  
7 -import org.apache.mina.filter.codec.textline.LineDelimiter;  
8 -import org.apache.mina.filter.codec.textline.TextLineCodecFactory;  
9 -import org.apache.mina.filter.executor.ExecutorFilter;  
10 -import org.apache.mina.filter.logging.LogLevel;  
11 -import org.apache.mina.filter.logging.LoggingFilter;  
12 -import org.apache.mina.transport.socket.nio.NioSocketAcceptor;  
13 -  
14 -import java.io.IOException;  
15 -import java.net.InetSocketAddress;  
16 -import java.nio.charset.Charset;  
17 -  
18 -/**  
19 - * @author dy  
20 - * @date 2021/3/3  
21 - */  
22 -public class MinaServer {  
23 -  
24 - public static ExecutorFilter executorFilter() {  
25 - //设置初始化线程数,最大线程数  
26 - ExecutorFilter executorFilter = new ExecutorFilter(10, 20);  
27 - return executorFilter;  
28 - }  
29 -  
30 - public static LoggingFilter loggingFilter() {  
31 - return new LoggingFilter();  
32 - }  
33 -  
34 - public static ProtocolCodecFilter protocolCodecFilter() {  
35 -// TextLineCodecFactory factory = new TextLineCodecFactory(Charset.forName("UTF-8"),  
36 -// LineDelimiter.WINDOWS.getValue(), LineDelimiter.WINDOWS.getValue());  
37 -  
38 -  
39 - //TextLineCodecFactory factory = new TextLineCodecFactory(Charset.forName("UTF-8"), LineDelimiter.WINDOWS.getValue(), LineDelimiter.WINDOWS.getValue());  
40 - ProtocolCodecFilter pcf = new ProtocolCodecFilter(new ByteFactory());  
41 - //ProtocolCodecFilter pcf = new ProtocolCodecFilter(factory);  
42 - return pcf;  
43 - }  
44 -  
45 - public static void main(String[] args) throws IOException {  
46 - /*IoAcceptor nio = new NioSocketAcceptor();  
47 - //设置缓冲区大小  
48 - nio.getSessionConfig().setReadBufferSize(2048);  
49 - //设置空闲状态时间,10秒没操作就进入空闲状态  
50 - nio.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);  
51 -  
52 - DefaultIoFilterChainBuilder def = new DefaultIoFilterChainBuilder();  
53 - def.addLast("executor", executorFilter());  
54 - def.addLast("logger", loggingFilter());  
55 - def.addLast("protocol", protocolCodecFilter());  
56 -  
57 - nio.setFilterChainBuilder(def);  
58 - nio.setHandler(new MinaServerHandler());  
59 - nio.bind(new InetSocketAddress(9098));*/  
60 -  
61 -  
62 -  
63 -  
64 -  
65 - //1、创建IoService,拥有监听是否有客户端链接  
66 - IoAcceptor acceptor = new NioSocketAcceptor();  
67 - //设置缓冲区大小  
68 - acceptor.getSessionConfig().setReadBufferSize(2048);  
69 - //设置空闲状态时间,10秒没操作就进入空闲状态  
70 - acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);  
71 -  
72 - //创建日志过滤器,mina内部使用的是slf4j日志,加入日志之后可以查看mina的运行细节信息  
73 - LoggingFilter log = new LoggingFilter();  
74 - log.setSessionOpenedLogLevel(LogLevel.INFO);  
75 - acceptor.getFilterChain().addLast("logger", log);  
76 -  
77 - //2、实现过滤器  
78 - //acceptor.getFilterChain().addLast("protocol", protocolCodecFilter());  
79 - acceptor.getFilterChain().addLast("protocol",  
80 - new ProtocolCodecFilter(  
81 - new TextLineCodecFactory(Charset.forName("UTF-8"), LineDelimiter.WINDOWS.getValue(), LineDelimiter.WINDOWS.getValue())  
82 - )  
83 - );  
84 - //3、实现IoHandler,并注册到IoService  
85 - acceptor.setHandler(new MinaServerHandler());  
86 - //绑定端口,绑定之前必须设置handler实现类  
87 - acceptor.bind(new InetSocketAddress(9098));  
88 -  
89 -  
90 - }  
91 -  
92 -}  
src/main/java/com/example/mina/mina/server/MinaServerHandler.java
@@ -1,141 +0,0 @@ @@ -1,141 +0,0 @@
1 -package com.example.mina.mina.server;  
2 -  
3 -import org.apache.mina.core.service.IoHandlerAdapter;  
4 -import org.apache.mina.core.session.IoSession;  
5 -  
6 -import java.io.ByteArrayOutputStream;  
7 -import java.io.ObjectOutputStream;  
8 -import java.net.SocketAddress;  
9 -import java.nio.charset.Charset;  
10 -import java.nio.charset.StandardCharsets;  
11 -  
12 -/**  
13 - * @author dy  
14 - * @date 2021/3/3  
15 - */  
16 -public class MinaServerHandler extends IoHandlerAdapter {  
17 -  
18 - @Override  
19 - public void messageReceived(IoSession session, Object message) throws Exception {  
20 -// String command = new String(ObjectToByte(message)).trim();  
21 -//  
22 -// if (command.startsWith("ATTN ALL MAX")) {//set all to max  
23 -// for (int i = 1; i < dataBuffer.getMaxRow(); i++) {  
24 -// dataBuffer.setOffset(i, dataBuffer.getMaxAtten());  
25 -// }  
26 -//  
27 -// return NONE;  
28 -// } else if (command.startsWith("ATTN?")) {//get  
29 -// String[] sss = command.split(" ");  
30 -// if (sss.length >= 2) {  
31 -// LogUtils.println(sss[0], sss[1]);  
32 -//  
33 -// int row = StrUtil.toInt(sss[1]);  
34 -// if (row >= 0 && row <= dataBuffer.getMaxRow()) {  
35 -// String str = String.valueOf(dataBuffer.getOffset(row));  
36 -// LogUtils.println("AeroflexVirtualBoxService::handleCommand return : ", str);  
37 -// return str.getBytes();  
38 -// }  
39 -// }  
40 -//  
41 -// return ERROR;  
42 -// } else if (command.startsWith("ATTN")) {//Set, Follow by ATTN?  
43 -// LogUtils.println("command.startsWith(\"ATTN\")");  
44 -// String[] aa = command.split(";");  
45 -//  
46 -// LogUtils.println(aa[0], aa[1]);  
47 -//  
48 -// String[] sss = aa[0].split(" ");  
49 -// StrUtil.printArray(sss);  
50 -//  
51 -// if (sss.length >= 3) {  
52 -// int row = StrUtil.toInt(sss[1]);  
53 -// int val = StrUtil.toInt(sss[2]);  
54 -//  
55 -// System.out.println(row + "/" + val);  
56 -//  
57 -//  
58 -// if (row >= 0 && row <= dataBuffer.getMaxRow()) {  
59 -// if (val >= 0 && val <= dataBuffer.getMaxAtten()) {  
60 -// dataBuffer.setOffset(row, val);  
61 -//  
62 -// String str = String.valueOf(dataBuffer.getOffset(row));  
63 -// LogUtils.println("handleCommand return =====> ", str);  
64 -// return str.getBytes();  
65 -// }  
66 -// }  
67 -// }  
68 -  
69 - //业务代码在这里编写处理  
70 - String str = new String((byte[])message);  
71 - System.out.println("The message received is [" + str + "]");  
72 - //获取客户端的连接地址  
73 - SocketAddress socketAddress = session.getRemoteAddress();  
74 - System.out.println(socketAddress);  
75 - String send = "消息已处理,你可以去玩了。。。";  
76 - //响应给对应客户端信息  
77 - session.write(send.getBytes());  
78 - session.closeNow();  
79 -// // 此处关闭session后客户端无法接收到服务器反馈的消息  
80 -// if (str.endsWith("quit")) {  
81 -// //注意:在这里调用close方法之后,只是关闭当前的tcp连接,server端还正常运行,  
82 -// //需要调用IoService的dispose方法才能关闭server端,client端同理  
83 -//  
84 -// return;  
85 -// }  
86 - }  
87 -  
88 - @Override  
89 - public void sessionCreated(IoSession session) throws Exception {  
90 - System.out.println("server session created");  
91 - super.sessionCreated(session);  
92 - }  
93 -  
94 - @Override  
95 - public void sessionOpened(IoSession session) throws Exception {  
96 - System.out.println("server session Opened");  
97 - super.sessionOpened(session);  
98 - }  
99 -  
100 - @Override  
101 - public void sessionClosed(IoSession session) throws Exception {  
102 - System.out.println("server session Closed");  
103 - super.sessionClosed(session);  
104 - }  
105 -  
106 - /**  
107 - * 在IoHandlerAdapter中有一个messageSent的方法,但是重写这个方法之后,不会发送数据,该方法只有数据发送成功之后才会调用,  
108 - * 所以在 messageReceived 方法中使用 session.write("消息已处理,你可以去玩了。。。"); 给客户端响应数据  
109 - *  
110 - * @param session  
111 - * @param message  
112 - * @throws Exception  
113 - */  
114 - @Override  
115 - public void messageSent(IoSession session, Object message) throws Exception {  
116 - // TODO Auto-generated method stub  
117 - System.out.println("发送数据成功了。。。" + message);  
118 - // session.write("testSent");  
119 - super.messageSent(session, message);  
120 - }  
121 -  
122 - private byte[] ObjectToByte(Object obj) {  
123 - byte[] bytes = null;  
124 - try {  
125 - // object to bytearray  
126 - ByteArrayOutputStream bo = new ByteArrayOutputStream();  
127 - ObjectOutputStream oo = new ObjectOutputStream(bo);  
128 - oo.writeObject(obj);  
129 -  
130 - bytes = bo.toByteArray();  
131 -  
132 - bo.close();  
133 - oo.close();  
134 - } catch (Exception e) {  
135 - System.out.println("translation" + e.getMessage());  
136 - e.printStackTrace();  
137 - }  
138 - return bytes;  
139 - }  
140 -  
141 -}  
src/main/java/com/example/mina/util/StrUtil.java 0 → 100644
@@ -0,0 +1,74 @@ @@ -0,0 +1,74 @@
  1 +package com.example.mina.util;
  2 +
  3 +public class StrUtil {
  4 +
  5 + private static final String[] EMPTY_ARRAY = new String[0];
  6 +
  7 + public static void main(String[] args) {
  8 + System.out.println(toInt("93"));
  9 +
  10 +// System.out.println(parseCommaInts("2a"));
  11 +
  12 + }
  13 +
  14 + public static int[] parseCommaInts(String str) {
  15 + if (str == null) {
  16 + return new int[0];
  17 + }
  18 +
  19 + String[] ss = str.split(",");
  20 + int[] ids = new int[ss.length];
  21 +
  22 + int count = 0;
  23 + for (int i = 0; i < ss.length; i++) {
  24 + int p = toInt(ss[i]);
  25 + ids[i] = p;
  26 + if (p >= 0) {
  27 + count++;
  28 + }
  29 + }
  30 +
  31 + if (count < ss.length) {
  32 + int[] ids2 = new int[count];
  33 + count = 0;
  34 + for (int i = 0; i < ss.length; i++) {
  35 + if (ids[i] >= 0) {
  36 + ids2[count++] = ids[i];
  37 + }
  38 + }
  39 +
  40 + ids = ids2;
  41 + }
  42 +
  43 + return ids;
  44 + }
  45 +
  46 + public static int toInt(String s) {
  47 + if (isEmpty(s)) {
  48 + return -1;
  49 + }
  50 +
  51 + try {
  52 + float f = Float.parseFloat(s.trim());
  53 + return (int) f;
  54 + } catch (Exception e) {
  55 + e.printStackTrace();
  56 + return -1;
  57 + }
  58 +
  59 + }
  60 +
  61 + public static void printArray(String[] ssss) {
  62 + if (ssss == null) {
  63 + System.out.println(" -- NULL --");
  64 + }
  65 + for (String s : ssss) {
  66 + System.out.println(s);
  67 + }
  68 + }
  69 +
  70 + public static boolean isEmpty(String s) {
  71 + return s == null || s.trim().isEmpty();
  72 + }
  73 +
  74 +}