SpringBoot使用Mina框架进行服务端与客户端数据通信

x33g5p2x  于2022-03-07 转载在 Spring  
字(2.8k)|赞(0)|评价(0)|浏览(501)

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;
	
	@Autowired
	ServerHandler serverHandler; //Mina事件类ServerHandler
	
	@Bean
	public 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 block
			e.printStackTrace();
		}
		System.out.println("Socket服务器在端口:" + port + "已经启动");
		return acceptor;
	}
}

Mina事件类ServerHandler

@Component
public class ServerHandler  extends IoHandlerAdapter {

    @Autowired
    MeterCollectsDataService meterCollectsDataService;
    @Autowired
    ElectricCollectorService electricCollectorService;

    @Override
    public void sessionCreated(IoSession session) throws Exception {
        session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, 60*5);
        String key = session.getRemoteAddress().toString();
        System.out.println("设备接入:" + key);
    }

    @Override
    public 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")));
    }

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        System.out.println("exceptionCaught");
        session.closeNow();
    }

    @Override
    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
        if (status == IdleStatus.BOTH_IDLE) {
            System.out.println("BOTH空闲");
            session.closeNow();
        }
    }

    @Override
    public void sessionClosed(IoSession session) throws Exception {
        System.out.println("sessionClosed");
        System.out.println("设备断开:" + session.getRemoteAddress().toString());
    }
}

调试

使用上传文件中的网络调试工具进行测试

相关文章