<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>
@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;
}
}
@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());
}
}
使用上传文件中的网络调试工具进行测试
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/qq_43842093/article/details/123192602
内容来源于网络,如有侵权,请联系作者删除!