概述
public class ChannelHandler extendsSimpleChannelHandler {private ConcurrentHashMap socket2ByteArrayMap = new ConcurrentHashMap<>();publicChannelHandler() {
}public voidmessageReceived(ChannelHandlerContext ctx, MessageEvent e) {
channels.add(e.getChannel());
ChannelBuffer buffer=(ChannelBuffer) e.getMessage();
logger.info(e.getRemoteAddress().toString());try{
SocketAddress curSocketAddress=e.getRemoteAddress();
ByteArrayOutputStream baos=socket2ByteArrayMap.get(curSocketAddress);if(baos == null){
baos= new ByteArrayOutputStream(2000);
socket2ByteArrayMap.put(curSocketAddress, baos);
}
baos.write(buffer.array());
}catch(IOException ie) {
Thread.currentThread().interrupt();
}
}public voidexceptionCaught(ChannelHandlerContext context, ExceptionEvent event) {
logger.error("Error", event.getCause());
Channel c=context.getChannel();
c.close().addListener(newChannelFutureListener() {
@Overridepublic void operationComplete(ChannelFuture future) throwsException {if(future.isSuccess())
channels.remove(future.getChannel());elselogger.error("FAILED to close channel");
}
});
}
@Overridepublic void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throwsException {
SocketAddress curSocketAddress=e.getChannel().getRemoteAddress();
ByteArrayOutputStream baos=socket2ByteArrayMap.remove(curSocketAddress);if(baos != null && baos.size() != 0){byte[] receivedBytes =baos.toByteArray();
receiver.receive(receivedBytes);
}super.channelClosed(ctx, e);
}
}
最后
以上就是疯狂小甜瓜为你收集整理的netty连接nbiot_利用netty实现支持高并发的Tcp短连接接收服务的全部内容,希望文章能够帮你解决netty连接nbiot_利用netty实现支持高并发的Tcp短连接接收服务所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复