当前位置:
首页 >
前端技术
> javascript
>内容正文
javascript
SpringBoot使用Mina框架进行服务端与客户端数据通信
生活随笔
收集整理的这篇文章主要介绍了
SpringBoot使用Mina框架进行服务端与客户端数据通信
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
pom.xml引入
<dependency><groupId>org.apache.mina</groupId><artifactId>mina-core</artifactId><version>2.1.3</version> </dependency> <dependency><groupId>org.apache.mina</groupId><artifactId>mina-integration-beans</artifactId><version>2.1.3</version> </dependency>服务端创建采集服务TCP线程
@Configuration public class TCPServ {//数据采集开关。配置项中获取@Value("${monitordata.company.electricity.enableSwitch}")private boolean enableSwitch = false;@Value("${monitordata.company.electricity.tcpPort}")private int port;@AutowiredServerHandler serverHandler; //Mina事件类ServerHandler@Beanpublic IoAcceptor companyElectricityTCPServ() throws Exception {if (!enableSwitch) {return null;}IoAcceptor acceptor = new NioSocketAcceptor();acceptor.getSessionConfig().setReadBufferSize(1024 * 1024);//设置缓冲区acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 60*5); //配置会话信息//其中需要注意的是,在服务端和客户端的代码里面,如果要传递string信息,codec编码过滤器中,要这么写:new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8")))。否则报错。//acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));acceptor.setHandler(serverHandler); //自定义处理业务的代码:自定义的类try {acceptor.bind(new InetSocketAddress(port));//绑定端口号} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("Socket服务器在端口:" + port + "已经启动");return acceptor;} }Mina事件类ServerHandler
@Component public class ServerHandler extends IoHandlerAdapter {@AutowiredMeterCollectsDataService meterCollectsDataService;@AutowiredElectricCollectorService electricCollectorService;@Overridepublic void sessionCreated(IoSession session) throws Exception {session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, 60*5);String key = session.getRemoteAddress().toString();System.out.println("设备接入:" + key);}@Overridepublic void messageReceived(IoSession session, Object message) throws Exception {String key = session.getRemoteAddress().toString();IoBuffer ioBuffer = (IoBuffer) message;byte[] data = new byte[ioBuffer.limit()];ioBuffer.get(data);String msg = new String(data);System.out.println("收到数据:" + msg);//发送数据String sendData = ""; session.write(IoBuffer.wrap(sendData.getBytes("utf-8")));}@Overridepublic void exceptionCaught(IoSession session, Throwable cause) throws Exception {System.out.println("exceptionCaught");session.closeNow();}@Overridepublic void sessionIdle(IoSession session, IdleStatus status) throws Exception {if (status == IdleStatus.BOTH_IDLE) {System.out.println("BOTH空闲");session.closeNow();}}@Overridepublic void sessionClosed(IoSession session) throws Exception {System.out.println("sessionClosed");System.out.println("设备断开:" + session.getRemoteAddress().toString());} }调试
使用上传文件中的网络调试工具进行测试
总结
以上是生活随笔为你收集整理的SpringBoot使用Mina框架进行服务端与客户端数据通信的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 【Python】Python 远程连接服
- 下一篇: 阮一峰的JavaScript 的 thi