一、概述
Mina官网:http://mina.apache.org/,这里面很多介绍我就不多说了,本文只是记录如何在后端通过srping boot +mina搭建后端服务,以及Android端如何与服务器简历链接的逻辑。
二、服务器端实现
服务器主要是使用spring boot实现的,通过config启动Mina,完整示例代码:https://github.com/stormdzh/MinaServer
@Slf4j
@Configuration
public class MinaConfig {
@Value("${mina.port1}")
private int port1;
@Value("${mina.port2}")
private int port2;
@Value("${mina.host}")
private String host;
@Bean
public LoggingFilter loggingFilter() {
return new LoggingFilter();
}
@Bean
public IoHandler ioHandler() {
return new ServerHandler();
}
@Bean
public IoAcceptor ioAcceptor() throws Exception {
IoAcceptor acceptor = new NioSocketAcceptor();
acceptor.getFilterChain().addLast("logger", loggingFilter());
// 使用自定义编码解码工厂类
// acceptor.getFilterChain().addLast("coderc", new ProtocolCodecFilter(new SocketFactory(Charset.forName("utf-8"))));
acceptor.getFilterChain().addLast("coderc", // 使用自定义编码解码工厂类
new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("GBK"))));//设置编码过滤器
acceptor.setHandler(ioHandler());
acceptor.getSessionConfig().setReadBufferSize(1024);
acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
SocketAddress addresses = new InetSocketAddress(host,port1);
SocketAddress addresses2 = new InetSocketAddress(host,port2);
acceptor.bind(new SocketAddress[] {addresses,addresses2});
log.info("=====================> Mina服务器在端口:" + port1+","+port2 + "已经启动!");
return acceptor;
}
}
三、客户端实现
客户端需要引入minasdk,之后创建连接,调用api发送信息,完整示例代码:https://github.com/stormdzh/MinaAndroidClient
1、创建连接
ConnectionConfig config = new ConnectionConfig.Builder(context)
// .setIp("192.168.1.8").setPort(10010)
.setIp(MinaConnfig.host).setPort(MinaConnfig.port)
.setReadBufferSize(1024).setConnectionTimeout(10000)
.builder();
manager = new ConnectionManager(config);
2、发送信息
String txt = "11111";
SessionManager.getInstance().writeToServer("1111");
addMessage(true, txt);
Log.e("tag", "send message to server");
网友评论