netty 广播
前端Ajax请求后端
后端代码
String msg = TcpIpUtils.ipPack(ip, port);
//
ByteBuf out = Unpooled.buffer();
byte[] bytes = HexUtils.fromHexString(msg);
out.writeBytes(bytes);
//广播-向所有客户端发送消息
ChannelGroupFuture channelFutures = MyChannelHandlerPool.channels.writeAndFlush(out)
.addListener(new ChannelGroupFutureListener() { // group监听器(注意单个监听器是ChannelFutureListener)
@Override
public void operationComplete(ChannelGroupFuture channelFutures) throws Exception {
if (channelFutures.isSuccess()) { // 发送消息成功
//保存到数据库
ipService.save(TcpIpUtils.getIpDO(ip,port));
}
} // 监听器
});
// todo 这里有点问题,这个done好像需要一点时间才能完成
// boolean done = channelFutures.isDone();
// boolean success = channelFutures.isSuccess();
// if (success) {
// return R.ok();
// } else {
// return R.error();
// }
不知道怎么搞的,好像是ajax请求的关系,现在领导又不做这个功能了,先放着吧
转码
/**
* 将ip转换为16进制
* @param ipString
* @return
*/
public static String ipToLong(String ipString) {
if(StringUtils.isBlank(ipString)){
return null;
}
String[] ip=ipString.split("\\.");
StringBuffer sb=new StringBuffer();
for (String str : ip) {
if (Integer.parseInt(str)<16) {
sb.append("0"+Integer.toHexString(Integer.parseInt(str)));
} else {
sb.append(Integer.toHexString(Integer.parseInt(str)));
}
}
return sb.toString();
}
crc16校验
/**
* 方法1-计算CRC16校验码
*
* @param bytes
* @return
*/
public static String getCRC(byte[] bytes) {
int CRC = 0x0000ffff;
int POLYNOMIAL = 0x0000a001;
int i, j;
for (i = 0; i < bytes.length; i++) {
CRC ^= ((int) bytes[i] & 0x000000ff);
for (j = 0; j < 8; j++) {
if ((CRC & 0x00000001) != 0) {
CRC >>= 1;
CRC ^= POLYNOMIAL;
} else {
CRC >>= 1;
}
}
}
//高低位转换(上面的CRC为:高位在前低位在后)
CRC = ( (CRC & 0x0000FF00) >> 8) | ( (CRC & 0x000000FF ) << 8);
// return Integer.toHexString(CRC);//小写
// return String.format("%04X", CRC);//大写
return String.format("%04x", CRC);//小写
}