countConnection();
- boolean sendLoading(String deviceName, Integer venueId,DeviceType deviceType, Integer memberId);
+ boolean sendLoading(String deviceName, Integer venueId, Integer memberId);
/**
* 出场
@@ -57,5 +56,5 @@ public interface MessageService {
*/
void enterVenue(String deviceName, Integer venueId, Integer memberId, Venue venue);
- void testLoad(String deviceName, Integer venueId,DeviceType deviceType);
+ void testLoad(String deviceName, Integer venueId);
}
diff --git a/api/src/main/java/com/sv/netty/netty/service/impl/AppMessageHandlerAdapter.java b/api/src/main/java/com/sv/netty/netty/service/impl/AppMessageHandlerAdapter.java
index d5863ee..df3feb1 100644
--- a/api/src/main/java/com/sv/netty/netty/service/impl/AppMessageHandlerAdapter.java
+++ b/api/src/main/java/com/sv/netty/netty/service/impl/AppMessageHandlerAdapter.java
@@ -1,6 +1,5 @@
package com.sv.netty.netty.service.impl;
-import com.enums.DeviceType;
import com.sv.entity.Member;
import com.sv.entity.MemberEnterVenueLog;
import com.sv.entity.Venue;
@@ -10,6 +9,7 @@ import com.sv.netty.netty.message.HeartBeat;
import com.sv.netty.netty.message.MessageDTO;
import com.sv.netty.netty.message.MessageType;
import com.sv.netty.netty.service.MessageService;
+import com.sv.netty.utils.JsonUtils;
import com.sv.service.api.MemberEnterVenueLogService;
import com.sv.service.api.MemberService;
import com.sv.service.api.VenueService;
@@ -52,7 +52,7 @@ public class AppMessageHandlerAdapter implements MessageService {
// @Resource
private MemberService memberService;
-// @Resource
+ @Resource
private VenueService venueService;
// @Resource
@@ -78,16 +78,16 @@ public class AppMessageHandlerAdapter implements MessageService {
*/
@Override
public void online(String clientId, Channel channel, HeartBeat heartBeat) {
- DeviceType deviceType = DeviceType.valueOf(heartBeat.getDeviceType());
+ logger.error("=========" + JsonUtils.encode(heartBeat) + clientId);
// 处理心跳信息
- if (!contains(heartBeat.getDeviceName(),heartBeat.getVenueId(),deviceType)){
+ if (!contains(heartBeat.getDeviceName(),heartBeat.getVenueId())){
// 此处存储客户端的channel 信息key 为 deviceId + venueId
Venue thisVenue = venueService.findById(heartBeat.getVenueId());
if (thisVenue == null ){
logger.error("this client choose venue Error! venueId == " + heartBeat.getVenueId());
} else {
- deviceService.online(heartBeat.getDeviceName(),heartBeat.getVenueId(),deviceType,thisVenue.getType(),clientId);
- putChannelType(heartBeat.getDeviceName(),heartBeat.getVenueId(),deviceType,channel);
+ deviceService.online(heartBeat.getDeviceName(),heartBeat.getVenueId(),thisVenue.getType(),clientId);
+ putChannelType(heartBeat.getDeviceName(),heartBeat.getVenueId(),channel);
MessageDTO messageDTO = new MessageDTO(MessageType.LINK,"欢迎扫码进场!");
channel.writeAndFlush(messageDTO);
}
@@ -100,10 +100,10 @@ public class AppMessageHandlerAdapter implements MessageService {
* @param venueId
*/
@Override
- public void Offline(String deviceName, Integer venueId,DeviceType deviceType) {
+ public void Offline(String deviceName, Integer venueId) {
if (deviceName != null && venueId != null){
- removeChannelType(deviceName,venueId,deviceType);
- deviceService.offline(deviceName,venueId,deviceType);
+ removeChannelType(deviceName,venueId);
+ deviceService.offline(deviceName,venueId);
}
}
@@ -113,12 +113,12 @@ public class AppMessageHandlerAdapter implements MessageService {
* @return
*/
@Override
- public boolean sendLoading(String deviceName, Integer venueId,DeviceType deviceType, Integer memberId) {
+ public boolean sendLoading(String deviceName, Integer venueId,Integer memberId) {
Member thisMember = memberService.findByMember(memberId);
if (thisMember!=null){
String nickname = thisMember.getNickname();
MessageDTO messageDTO = new MessageDTO(MessageType.LOAD,"欢迎光临!" + nickname + ",请您60s内操作进场。");
- Channel currentChannel = getCurrentChannel(deviceName, venueId, deviceType);
+ Channel currentChannel = getCurrentChannel(deviceName, venueId);
sendMessage(currentChannel,messageDTO);
return true;
}
@@ -130,15 +130,15 @@ public class AppMessageHandlerAdapter implements MessageService {
* @return
*/
@Override
- public void testLoad(String deviceName, Integer venueId,DeviceType deviceType) {
- Channel currentChannel = getCurrentChannel(deviceName, venueId, deviceType);
- currentChannel.writeAndFlush("Test Links" + deviceName + venueId + deviceType);
+ public void testLoad(String deviceName, Integer venueId) {
+ Channel currentChannel = getCurrentChannel(deviceName, venueId);
+ currentChannel.writeAndFlush("Test Links" + deviceName + venueId);
}
@Override
public void outVenue(String deviceName, Integer venueId, Integer memberId, Venue venue) {
- Channel channel = getCurrentChannel(deviceName,venueId,DeviceType.OUT);
+ Channel channel = getCurrentChannel(deviceName,venueId);
Member member = memberService.findByMember(memberId);
if (member != null) {
//出场 不用判断直接出
@@ -181,7 +181,7 @@ public class AppMessageHandlerAdapter implements MessageService {
@Override
public void enterVenue(String deviceName, Integer venueId, Integer memberId, Venue venue) {
Member member = memberService.findByMember(memberId);
- Channel channel = getCurrentChannel(deviceName, venueId, DeviceType.ENTER);
+ Channel channel = getCurrentChannel(deviceName, venueId);
// 校验入场时间是否正常
if (checkInterval(member,venueId)) {
if(venueService.qrCodeEnterVenue(memberId,deviceName,venueId,venue)){
@@ -208,7 +208,7 @@ public class AppMessageHandlerAdapter implements MessageService {
MemberEnterVenueLog enterVenueLog = memberEnterVenueLogService.findMemberLastLogNoType(member.getId(), venueId);
if (enterVenueLog != null) {
//有记录 查看 最后一次是否是出场
- if (enterVenueLog.getType().intValue() == DeviceType.OUT.getCode()) {
+ if (true) {// TODO
return true;
} else {
//是进场
@@ -272,32 +272,32 @@ public class AppMessageHandlerAdapter implements MessageService {
/**
* 缓存通道
*/
- public void putChannelType(String deviceName, Integer venueId, DeviceType deviceType, Channel channel) {
- String clientId = deviceName + Constant.SPIT_WORD + venueId + Constant.SPIT_WORD + deviceType;
+ public void putChannelType(String deviceName, Integer venueId, Channel channel) {
+ String clientId = deviceName + Constant.SPIT_WORD + venueId;
links.put(clientId, channel);
}
/**
* 获取当前通道
*/
- public Channel getCurrentChannel(String deviceName, Integer venueId, DeviceType deviceType){
- String clientId = deviceName + Constant.SPIT_WORD + venueId + Constant.SPIT_WORD + deviceType;
+ public Channel getCurrentChannel(String deviceName, Integer venueId){
+ String clientId = deviceName + Constant.SPIT_WORD + venueId + Constant.SPIT_WORD;
return links.get(clientId);
}
/**
* 获取通道
*/
- public boolean contains(String deviceName, Integer venueId, DeviceType deviceType) {
- String clientId = deviceName + Constant.SPIT_WORD + venueId + Constant.SPIT_WORD + deviceType;
+ public boolean contains(String deviceName, Integer venueId) {
+ String clientId = deviceName + Constant.SPIT_WORD + venueId + Constant.SPIT_WORD;
return links.containsKey(clientId);
}
/**
* 移除通道
*/
- public void removeChannelType(String deviceName, Integer venueId, DeviceType deviceType) {
- String clientId = deviceName + Constant.SPIT_WORD + venueId + Constant.SPIT_WORD + deviceType;
+ public void removeChannelType(String deviceName, Integer venueId) {
+ String clientId = deviceName + Constant.SPIT_WORD + venueId ;
links.remove(clientId);
}
diff --git a/api/src/main/java/com/sv/netty/utils/CommonUtils.java b/api/src/main/java/com/sv/netty/utils/CommonUtils.java
deleted file mode 100644
index 7d72218..0000000
--- a/api/src/main/java/com/sv/netty/utils/CommonUtils.java
+++ /dev/null
@@ -1,76 +0,0 @@
-package com.sv.netty.utils;
-
-import java.nio.charset.Charset;
-
-/**
- * USER: douya
- * DATE: 2017-08-28
- */
-public class CommonUtils {
-
-
-
- public static byte[] intToBytes2(int n){
- byte[] b = new byte[4];
-
- for(int i = 0;i < 4;i++)
- {
- b[i]=(byte)(n>>(24-i*8));
-
- }
- return b;
- }
-
- /**
- * byte数组转换成16进制字符串
- * @param src
- * @return
- */
- public static String bytesToHexString(byte[] src){
- StringBuilder stringBuilder = new StringBuilder();
- if (src == null || src.length <= 0) {
- return null;
- }
- for (int i = 0; i < src.length; i++) {
- int v = src[i] & 0xFF;
- String hv = Integer.toHexString(v);
- if (hv.length() < 2) {
- stringBuilder.append(0);
- }
- stringBuilder.append(hv);
- }
- return stringBuilder.toString();
- }
-
- /**
- * byte数组转换成16进制字符数组
- * @param src
- * @return
- */
- public static String[] bytesToHexStrings(byte[] src){
- if (src == null || src.length <= 0) {
- return null;
- }
- String[] str = new String[src.length];
-
- for (int i = 0; i < src.length; i++) {
- int v = src[i] & 0xFF;
- String hv = Integer.toHexString(v);
- if (hv.length() < 2) {
- str[i] = "0";
- }
- str[i] = hv;
- }
- return str;
- }
-
-
- public static void main(String[] arg){
- String message = "{\"cmd\":\"text_message\",\"content\":\"开心开心\",\"member_count\":0,\"system\":0,\"vmc_no\":\"322af403825a\"";
- byte[] bodys = message.getBytes(Charset.forName("UTF-8"));
- String magic = bytesToHexString("doll".getBytes(Charset.forName("UTF-8")));
- String length = bytesToHexString(intToBytes2(bodys.length+8));
- System.out.println(magic+length+bytesToHexString(bodys));
- }
-
-}
diff --git a/api/src/main/java/com/sv/netty/utils/EncodeUtils.java b/api/src/main/java/com/sv/netty/utils/EncodeUtils.java
deleted file mode 100644
index 7507d59..0000000
--- a/api/src/main/java/com/sv/netty/utils/EncodeUtils.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/**
- * Copyright (c) 2005-2009 springside.org.cn
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- *
- * $Id: EncodeUtils.java 984 2010-03-21 13:02:44Z calvinxiu $
- */
-package com.sv.netty.utils;
-
-import org.apache.commons.codec.DecoderException;
-import org.apache.commons.codec.binary.Base64;
-import org.apache.commons.codec.binary.Hex;
-
-/**
- * 各种格式的编码加码工具类.
- *
- * 集成Commons-Codec,Commons-Lang及JDK提供的编解码方法.
- *
- * @author ranfi
- */
-public class EncodeUtils {
-
- private static final String DEFAULT_URL_ENCODING = "UTF-8";
- private static final char[] BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
-
- /**
- * Hex编码.
- */
- public static String encodeHex(byte[] input) {
- return Hex.encodeHexString(input);
- }
-
- /**
- * Hex解码.
- */
- public static byte[] decodeHex(String input) {
- try {
- return Hex.decodeHex(input.toCharArray());
- } catch (DecoderException e) {
- return null;
- }
- }
-
- /**
- * Base64编码.
- */
- public static String encodeBase64(byte[] input) {
- return Base64.encodeBase64String(input);
- }
-
- /**
- * Base64编码, URL安全(将Base64中的URL非法字符'+'和'/'转为'-'和'_', 见RFC3548).
- */
- public static String encodeUrlSafeBase64(byte[] input) {
- return Base64.encodeBase64URLSafeString(input);
- }
-
- /**
- * Base64解码.
- */
- public static byte[] decodeBase64(String input) {
- return Base64.decodeBase64(input);
- }
-
- /**
- * Base62编码。
- */
- public static String encodeBase62(byte[] input) {
- char[] chars = new char[input.length];
- for (int i = 0; i < input.length; i++) {
- chars[i] = BASE62[(input[i] & 0xFF) % BASE62.length];
- }
- return new String(chars);
- }
-
-
-}
diff --git a/api/src/main/java/com/sv/netty/utils/JsonMapper.java b/api/src/main/java/com/sv/netty/utils/JsonMapper.java
deleted file mode 100644
index b4d736d..0000000
--- a/api/src/main/java/com/sv/netty/utils/JsonMapper.java
+++ /dev/null
@@ -1,204 +0,0 @@
-/**
- * Copyright (c) 2005-2012 springside.org.cn
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- */
-package com.sv.netty.utils;
-
-import com.fasterxml.jackson.annotation.JsonInclude.Include;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.DeserializationFeature;
-import com.fasterxml.jackson.databind.JavaType;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.SerializationFeature;
-import com.fasterxml.jackson.databind.util.JSONPObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.util.StringUtils;
-
-import java.io.IOException;
-import java.util.Collection;
-import java.util.Map;
-
-/**
- * 简单封装Jackson,实现JSON String<->Java Object的Mapper.
- *
- * 封装不同的输出风格, 使用不同的builder函数创建实例.
- *
- * @author calvin
- */
-public class JsonMapper {
-
- private static Logger logger = LoggerFactory.getLogger(JsonMapper.class);
-
- private final ObjectMapper mapper;
-
- public JsonMapper() {
- this(null);
- }
-
- public JsonMapper(Include include) {
- mapper = new ObjectMapper();
- // 设置输出时包含属性的风格
- if (include != null) {
- mapper.setSerializationInclusion(include);
- }
- // 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
- mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
- }
-
- /**
- * 创建只输出非Null且非Empty(如List.isEmpty)的属性到Json字符串的Mapper,建议在外部接口中使用.
- */
- public static JsonMapper nonEmptyMapper() {
- return new JsonMapper(Include.NON_EMPTY);
- }
-
- /**
- * 创建只输出初始值被改变的属性到Json字符串的Mapper, 最节约的存储方式,建议在内部接口中使用。
- */
- public static JsonMapper nonDefaultMapper() {
- return new JsonMapper(Include.NON_DEFAULT);
- }
-
- public static JsonMapper nonNullMapper() {
- return new JsonMapper(Include.NON_NULL);
- }
-
- /**
- * Object可以是POJO,也可以是Collection或数组。 如果对象为Null, 返回"null". 如果集合为空集合, 返回"[]".
- */
- public String toJson(Object object) {
-
- try {
- return mapper.writeValueAsString(object);
- } catch (IOException e) {
- logger.warn("write to json string error:" + object, e);
- return null;
- }
- }
-
- /**
- * 反序列化POJO或简单Collection如List.
- *
- * 如果JSON字符串为Null或"null"字符串, 返回Null. 如果JSON字符串为"[]", 返回空集合.
- *
- * 如需反序列化复杂Collection如List, 请使用fromJson(String, JavaType)
- *
- * @see #fromJson(String, JavaType)
- */
- public T fromJson(String jsonString, Class clazz) {
- if (StringUtils.isEmpty(jsonString)) {
- return null;
- }
-
- try {
- return mapper.readValue(jsonString, clazz);
- } catch (IOException e) {
- logger.warn("parse json string error:" + jsonString, e);
- return null;
- }
- }
-
- /**
- * 反序列化复杂Collection如List,
- * 先使用createCollectionType()或contructMapType()构造类型, 然后调用本函数.
- *
- * @see #createCollectionType(Class, Class...)
- */
- public T fromJson(String jsonString, JavaType javaType) {
- if (StringUtils.isEmpty(jsonString)) {
- return null;
- }
-
- try {
- return (T) mapper.readValue(jsonString, javaType);
- } catch (IOException e) {
- logger.warn("parse json string error:" + jsonString, e);
- return null;
- }
- }
-
- /**
- * 构造Collection类型.
- */
- public JavaType contructCollectionType(Class extends Collection> collectionClass, Class> elementClass) {
- return mapper.getTypeFactory().constructCollectionType(collectionClass, elementClass);
- }
-
- /**
- * 构造Map类型.
- */
- public JavaType contructMapType(Class extends Map> mapClass, Class> keyClass, Class> valueClass) {
- return mapper.getTypeFactory().constructMapType(mapClass, keyClass, valueClass);
- }
-
- /**
- * map 转 bean
- *
- * @param map
- * @param beanClass
- * @return
- */
- public T convertMapToBean(Map map, Class beanClass) {
- try {
- return mapper.convertValue(map, beanClass);
- } catch (Exception e) {
- logger.warn("convertMapToBean error! ", e);
- }
- return null;
- }
-
- /**
- * map 转 bean
- *
- * @param bean
- * @param objectClass
- * @return
- */
- public T convertBeanToOther(Object bean, Class objectClass) {
- try {
- return mapper.convertValue(bean, objectClass);
- } catch (Exception e) {
- logger.warn("convertMapToBean error! ", e);
- }
- return null;
- }
-
- /**
- * 当JSON里只含有Bean的部分屬性時,更新一個已存在Bean,只覆蓋該部分的屬性.
- */
- public void update(String jsonString, Object object) {
- try {
- mapper.readerForUpdating(object).readValue(jsonString);
- } catch (JsonProcessingException e) {
- logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
- } catch (IOException e) {
- logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
- }
- }
-
- /**
- * 輸出JSONP格式數據.
- */
- public String toJsonP(String functionName, Object object) {
- return toJson(new JSONPObject(functionName, object));
- }
-
- /**
- * 設定是否使用Enum的toString函數來讀寫Enum, 為False時時使用Enum的name()函數來讀寫Enum, 默認為False.
- * 注意本函數一定要在Mapper創建後, 所有的讀寫動作之前調用.
- */
- public void enableEnumUseToString() {
- mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
- mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
- }
-
- /**
- * 取出Mapper做进一步的设置或使用其他序列化API.
- */
- public ObjectMapper getMapper() {
- return mapper;
- }
-
-}
diff --git a/api/src/main/java/com/sv/netty/utils/JsonUtils.java b/api/src/main/java/com/sv/netty/utils/JsonUtils.java
deleted file mode 100644
index 250c659..0000000
--- a/api/src/main/java/com/sv/netty/utils/JsonUtils.java
+++ /dev/null
@@ -1,94 +0,0 @@
-package com.sv.netty.utils;
-
-import com.fasterxml.jackson.core.JsonGenerationException;
-import com.fasterxml.jackson.core.JsonParseException;
-import com.fasterxml.jackson.core.JsonParser;
-import com.fasterxml.jackson.core.type.TypeReference;
-import com.fasterxml.jackson.databind.DeserializationFeature;
-import com.fasterxml.jackson.databind.JsonMappingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.IOException;
-
-/**
- * USER: douya
- * DATE: 2017-11-01
- */
-public class JsonUtils {
-
-
- /**
- * Logger for this class
- */
- private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class);
-
- private final static ObjectMapper objectMapper = new ObjectMapper();
-
- static {
- objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
- objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
- objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
- objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
- objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- }
-
- private JsonUtils() {
- }
-
- public static String encode(Object obj) {
- try {
- return objectMapper.writeValueAsString(obj);
- } catch (JsonGenerationException e) {
- logger.error("encode(Object)", e); //$NON-NLS-1$
- } catch (JsonMappingException e) {
- logger.error("encode(Object)", e); //$NON-NLS-1$
- } catch (IOException e) {
- logger.error("encode(Object)", e); //$NON-NLS-1$
- }
- return null;
- }
-
- /**
- * 将json string反序列化成对象
- *
- * @param json
- * @param valueType
- * @return
- */
- public static T decode(String json, Class valueType) {
- try {
- return objectMapper.readValue(json, valueType);
- } catch (JsonParseException e) {
- logger.error("decode(String, Class)", e);
- } catch (JsonMappingException e) {
- logger.error("decode(String, Class)", e);
- } catch (IOException e) {
- logger.error("decode(String, Class)", e);
- }
- return null;
- }
-
- /**
- * 将json array反序列化为对象
- *
- * @param json
- * @param typeReference
- * @return
- */
- @SuppressWarnings("unchecked")
- public static T decode(String json, TypeReference typeReference) {
- try {
- return (T) objectMapper.readValue(json, typeReference);
- } catch (JsonParseException e) {
- logger.error("decode(String, JsonTypeReference)", e);
- } catch (JsonMappingException e) {
- logger.error("decode(String, JsonTypeReference)", e);
- } catch (IOException e) {
- logger.error("decode(String, JsonTypeReference)", e);
- }
- return null;
- }
-
-}
diff --git a/entity/src/main/java/com/enums/DeviceType.java b/entity/src/main/java/com/enums/DeviceType.java
deleted file mode 100644
index 44a5e76..0000000
--- a/entity/src/main/java/com/enums/DeviceType.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package com.enums;
-
-/**
- * 设备属性,控制入场还是控制出场
- */
-public enum DeviceType {
-
- ENTER(0,"进场"),
- OUT(1,"出场");
- private int code;
- private String name;
-
- DeviceType(int code, String name) {
- this.code = code;
- this.name = name;
- }
-
- public int getCode() {
- return code;
- }
-
- public void setCode(int code) {
- this.code = code;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-}
diff --git a/entity/src/main/java/com/sv/entity/Device.java b/entity/src/main/java/com/sv/entity/Device.java
index 0267515..2e7c295 100644
--- a/entity/src/main/java/com/sv/entity/Device.java
+++ b/entity/src/main/java/com/sv/entity/Device.java
@@ -1,7 +1,5 @@
package com.sv.entity;
-import com.enums.DeviceType;
-
import java.io.Serializable;
import java.util.Date;
@@ -15,7 +13,7 @@ public class Device implements Serializable {
/**
- *
+ *
*/
private Integer id;
@@ -38,8 +36,6 @@ public class Device implements Serializable {
private Integer venueType;
- private DeviceType deviceType;
-
private Integer bindMember;
private Date bindTime;
@@ -75,7 +71,7 @@ public class Device implements Serializable {
/**
* 设置
*
- * @param id
+ * @param id
*/
public void setId(Integer id){
this.id = id;
@@ -84,7 +80,7 @@ public class Device implements Serializable {
/**
* 获取
*
- * @return
+ * @return
*/
public Integer getId(){
return id;
@@ -249,14 +245,6 @@ public class Device implements Serializable {
this.venueType = venueType;
}
- public DeviceType getDeviceType() {
- return deviceType;
- }
-
- public void setDeviceType(DeviceType deviceType) {
- this.deviceType = deviceType;
- }
-
public Integer getBindMember() {
return bindMember;
}
@@ -272,4 +260,4 @@ public class Device implements Serializable {
public void setBindTime(Date bindTime) {
this.bindTime = bindTime;
}
-}
\ No newline at end of file
+}
diff --git a/netty-client/pom.xml b/netty-client/pom.xml
index 678ae87..516c21c 100644
--- a/netty-client/pom.xml
+++ b/netty-client/pom.xml
@@ -13,13 +13,8 @@
- io.netty
- netty-all
- 4.1.10.Final
-
-
- org.springframework.boot
- spring-boot-starter-web
+ smartvenue
+ netty-model
diff --git a/netty-client/src/main/java/com/sv/netty/ClientHandler.java b/netty-client/src/main/java/com/sv/netty/ClientHandler.java
index 49796eb..29ab9b5 100644
--- a/netty-client/src/main/java/com/sv/netty/ClientHandler.java
+++ b/netty-client/src/main/java/com/sv/netty/ClientHandler.java
@@ -1,14 +1,16 @@
package com.sv.netty;
import com.sv.netty.message.HeartBeat;
-import com.sv.netty.message.MessageType;
-import com.sv.netty.message.VenueMessage;
+import com.sv.netty.utils.EncodeMsg;
+import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.ChannelInboundHandlerAdapter;
+import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
+import java.net.UnknownHostException;
+
/**
* 通讯服务器请求处理
*
@@ -16,77 +18,82 @@ import io.netty.handler.timeout.IdleStateEvent;
* @date 05/12/2017 10:27 PM
*/
@ChannelHandler.Sharable
-public class ClientHandler extends ChannelInboundHandlerAdapter {
-
- private final static String TAG = "ClientHandler";
-
- private boolean hasRead = false;
-
- @Override
- public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
- super.channelRegistered(ctx);
-// ClientTcpSession.getInstance().setContext(ctx);
- }
-
- @Override
- public void channelActive(ChannelHandlerContext ctx) throws Exception {
- super.channelActive(ctx);
- //服务器连上以后立即模拟心跳返回
- ctx.writeAndFlush(getHbMessage());
- }
-
- @Override
- public void channelInactive(ChannelHandlerContext ctx) throws Exception {
- super.channelInactive(ctx);
- ClientThread.getInstance().clearFuture();
- ClientThread.getInstance().restart();
- }
-
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
- super.channelRead(ctx, msg);
-// Message message = JsonMapper.fromJson(msg.toString(), Message.class);
-// MessageService.getInstance().execute(message);
- }
-
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
- super.exceptionCaught(ctx, cause);
- System.err.println("错了Error");
- System.err.println("Error");
-// GlobalConfig.isConnected = false;
- ctx.close();
- }
+public class ClientHandler extends SimpleChannelInboundHandler {
/**
- * 获取心跳返回消息
- *
- * @return
- */
- private VenueMessage getHbMessage() {
- HeartBeat hb = new HeartBeat();
-// hb.setVersionCode(AppUtil.getVersionCode(StartApplication.getAppContext()));
- VenueMessage message = new VenueMessage();
- message.setMessageType(MessageType.HB);
-// message.setDeviceId(DeviceIdUtil.generateDeviceId(mContext));
- return message;
- }
-
- /**
- * 心跳处理
- *
+ * 当通道就绪就会触发
* @param ctx
- * @param evt
* @throws Exception
*/
@Override
- public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
+ public void channelActive(ChannelHandlerContext ctx) throws Exception {
+ super.channelActive(ctx);
+ }
+
+ /**
+ * 当通道失效就会触发
+ * @param ctx
+ * @throws Exception
+ */
+ @Override
+ public void channelInactive(ChannelHandlerContext ctx) throws Exception {
+ super.channelInactive(ctx);
+ }
+
+ /**
+ * 当通道有读取事件时触发
+ * @param ctx
+ * @param msg
+ * @throws Exception
+ */
+ @Override
+ public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
+ System.out.println("接收服务器响应msg:[" + msg + "]");
+// MessageDTO message = JsonMapper.fromJson(msg, MessageDTO.class);
+// MessageService.getInstance().execute(message);
+ }
+
+ /**
+ * 心跳
+ * @param ctx
+ * @param evt
+ */
+ @Override
+ public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws UnknownHostException {
if (IdleStateEvent.class.isAssignableFrom(evt.getClass())) {
IdleStateEvent event = (IdleStateEvent) evt;
if (event.state() == IdleState.ALL_IDLE) {
- ctx.writeAndFlush(getHbMessage());
+ ctx.write(EncodeMsg.INSTANCE.encode(getHbMessage()));
+ ctx.flush();
}
}
}
+ /**
+ * 封装心跳请求包
+ * @throws Exception
+ */
+ private HeartBeat getHbMessage() {
+ HeartBeat hb = new HeartBeat();
+ hb.setDeviceName("dsadasdasd");
+ hb.setVenueId(123);
+ return hb;
+ }
+
+ /**
+ * 处理异常
+ * @param ctx
+ * @param cause
+ * @throws Exception
+ */
+ @Override
+ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
+ System.out.println("ClientHandler exceptionCaught");
+ cause.printStackTrace();
+ Channel channel = ctx.channel();
+ if(channel.isActive()) {
+ ctx.close();
+ }
+ }
+
}
diff --git a/netty-client/src/main/java/com/sv/netty/ClientInitializer.java b/netty-client/src/main/java/com/sv/netty/ClientInitializer.java
index b6e8e32..b1d9ba1 100644
--- a/netty-client/src/main/java/com/sv/netty/ClientInitializer.java
+++ b/netty-client/src/main/java/com/sv/netty/ClientInitializer.java
@@ -1,19 +1,18 @@
package com.sv.netty;
-import com.sv.netty.config.Constant;
-import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
-import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
+import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
+import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
public class ClientInitializer extends ChannelInitializer {
- private final static int TIME_HEART_BEAT = 20;
+ private final static int TIME_HEART_BEAT = 5;
public ClientThread.ReConnectHandler reConnectHandler;
public ClientHandler dmClientHandler;
@@ -28,10 +27,10 @@ public class ClientInitializer extends ChannelInitializer {
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("reconnect", reConnectHandler);
- pipeline.addLast("idleStateHandler", new IdleStateHandler(TIME_HEART_BEAT, TIME_HEART_BEAT, TIME_HEART_BEAT));
- pipeline.addLast(new MessageEncoder());
- pipeline.addFirst(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 4, 4, 0, 0));
- pipeline.addLast(new MessageDecoder());
+ pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
+ pipeline.addLast(new StringDecoder());
+ pipeline.addLast(new StringEncoder());
+ pipeline.addLast(new IdleStateHandler(TIME_HEART_BEAT, TIME_HEART_BEAT,TIME_HEART_BEAT));
pipeline.addLast(dmClientHandler);
}
diff --git a/netty-client/src/main/java/com/sv/netty/ClientThread.java b/netty-client/src/main/java/com/sv/netty/ClientThread.java
index 87ba1cd..f6c2abc 100644
--- a/netty-client/src/main/java/com/sv/netty/ClientThread.java
+++ b/netty-client/src/main/java/com/sv/netty/ClientThread.java
@@ -1,10 +1,11 @@
package com.sv.netty;
-import com.sv.netty.config.Constant;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
+import io.netty.handler.logging.LoggingHandler;
+
import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;
@@ -51,6 +52,7 @@ public class ClientThread extends Thread{
bootstrap = new Bootstrap();
bootstrap.group(workerGroup);
bootstrap.channel(NioSocketChannel.class);
+ bootstrap.handler(new LoggingHandler());
bootstrap.option(ChannelOption.TCP_NODELAY, true);
bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
@@ -114,7 +116,7 @@ public class ClientThread extends Thread{
public void run() {
doConnect();
}
- }, 1, TimeUnit.SECONDS);
+ }, 2, TimeUnit.SECONDS);
}
}
diff --git a/netty-client/src/main/java/com/sv/netty/MessageDecoder.java b/netty-client/src/main/java/com/sv/netty/MessageDecoder.java
deleted file mode 100644
index 6c79def..0000000
--- a/netty-client/src/main/java/com/sv/netty/MessageDecoder.java
+++ /dev/null
@@ -1,48 +0,0 @@
-package com.sv.netty;
-
-import com.sv.netty.config.Constant;
-import io.netty.buffer.ByteBuf;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.handler.codec.ByteToMessageDecoder;
-
-import java.io.UnsupportedEncodingException;
-import java.util.List;
-
-/**
- * Created by hehelt on 16/2/26.
- *
- * 解码器
- */
-public class MessageDecoder extends ByteToMessageDecoder {
-
- @Override
- protected void decode(ChannelHandlerContext ctx, ByteBuf in, List