堕落不振功业废,勤耕不辍日月新

自定义serverSocket线程池,处理并发链接

综合 hailen 20℃

自定义serverSocket线程池,处理并发链接

2018年06月11日 16:59:02 samHuangLiang 阅读数:271
 版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/samHuangLiang/article/details/80654484
  1. public class AppServerSocket {
  2. private Integer port;
  3. private static ServerSocket serverSocket;
  4. public AppServerSocket(Integer port) {
  5. this.port = port;
  6. try {
  7. start();
  8. } catch (IOException e) {
  9. e.printStackTrace();
  10. }
  11. }
  12. /**
  13. * 接受连接
  14. */
  15. public void start() throws IOException {
  16. serverSocket = new ServerSocket(port);
  17. new Thread(new Runnable() {
  18. @Override
  19. public void run() {
  20. while (true) {
  21. try {
  22. Socket socket = serverSocket.accept();
  23. handleSocket(socket);
  24. } catch (IOException e) {
  25. e.printStackTrace();
  26. }
  27. }
  28. }
  29. }).start();
  30. }
  31. /**
  32. * 处理连接
  33. * @param socket
  34. */
  35. public static void handleSocket(Socket socket) {
  36. new Thread(new Runnable() {
  37. @Override
  38. public void run() {
  39. try {
  40. MessageHandler.sendMessage(socket.getOutputStream(), “test”, new HashMap<>());
  41. String message = MessageHandler.parseMessage(socket.getInputStream());
  42. if (isNotEmpty(appIdMessageDto)) {
  43. if (appIdMessageDto.isSuccess()) {
  44. //添加到SocketPools中
  45. SocketHandler.addScoket(appId, socket);
  46. }
  47. }
  48. } catch (IOException e) {
  49. e.printStackTrace();
  50. } catch (Exception e) {
  51. System.out.println(“—————-” + e.getMessage());
  52. }
  53. }
  54. }).start();
  55. }
  56. }

  1. public class MessageHandler {
  2. private static final String key = “***********************”;
  3. private static final Logger LOGGER = LoggerFactory.getLogger(MessageHandler.class);
  4. //发送数据到客户端
  5. public static void sendMessage(OutputStream os, String command, Map<String, String> data) {
  6. try {
  7. Map<String, Object> params = new HashMap<>();
  8. params.put(“command”, command);
  1.       //签名
  2. String sign = getSign(data);
  3. params.put(“sign”, sign);
  4. LOGGER.debug(“——-send—-sign——–” + sign);
  5. if (isNotEmpty(data)) {
  6. params.put(“data”, JSON.toJSONString(data));
  7. } else {
  8. params.put(“data”, “”);
  9. }
  10. DataOutputStream out = new DataOutputStream(os);
  11. StringBuilder str = new StringBuilder();
  12. out.writeUTF(JSON.toJSONString(params ));
  13. } catch (IOException e) {
  14. e.printStackTrace();
  15. }
  16. }
  17. public static void sendMessage(String appId, String command, Map<String, String> data) {
  18. Socket socket = SocketHandler.getSocket(appId);
  19. if (isEmpty(socket)) {
  20. throw new MonkeyException(“socket is empty”);
  21. }
  22. try {
  23. sendMessage(socket.getOutputStream(), command, data);
  24. } catch (IOException e) {
  25. e.printStackTrace();
  26. }
  27. }
  28. //获取客户端返回的消息
  29. public static String parseMessage(String appId) throws Exception {
  30. Socket socket = SocketHandler.getSocket(appId);
  31. DataInputStream in = new DataInputStream(socket.getInputStream());
  32. String message = in.readUTF();
  33. String messageString = checkMessageString(message);
  34. if (!resultCheckSign(messageString)) {
  35. throw new Exception(“sign error”);
  36. }
  37. return messageString;
  38. }
  39. public static String checkMessageString(String message) {
  40. if (isNotEmpty(message)) {
  41. if (message.startsWith(“***”) && message.endsWith(“***”)) {
  42. int start = message.indexOf(“{“);
  43. int end = message.lastIndexOf(“}”);
  44. String substring = message.substring(start, end + 1);
  45. return substring;
  46. }
  47. }
  48. throw new Exception(“返回的消息不完整”);
  49. }
  50. public static String parseMessage(InputStream inputStream) throws Exception {
  51. DataInputStream in = new DataInputStream(inputStream);
  52. String message = in.readUTF();
  53. String messageString = checkMessageString(message);
  54. if (!resultCheckSign(messageString)) {
  55. throw new Exception(“sign error”);
  56. }
  57. return messageString;
  58. }
  59. public static Boolean resultCheckSign(String message) {
  60. JSONObject jsonObject = JSON.parseObject(message);
  61. if (isNotEmpty(jsonObject)) {
  62. String sign = jsonObject.getString(“sign”);
  63. LOGGER.debug(“——–return–sign——–” + sign);
  64. String dataStr = jsonObject.getString(“data”);
  65. if (isNotEmpty(dataStr)) {
  66. return SignUtils.checkRoadGateSign(dataStr, key, sign);
  67. } else {
  68. return SignUtils.checkRoadGateSign(“”, key, sign);
  69. }
  70. }
  71. return false;
  72. }
  73. public static String getSign(Map<String, String> data) {
  74. String preStr = “”;
  75. if (isNotEmpty(data)) {
  76. preStr = JSON.toJSONString(data);
  77. String sign = MD5.sign(preStr, “&salt=” + key, “utf-8”);
  78. return sign;
  79. }

  1. public class SocketHandler {
  2. private static ConcurrentMap<String, Socket> socketPools = new ConcurrentHashMap<>();
  3. public static void addScoket(String appId, Socket socket) {
  4. socketPools.put(appId, socket);
  5. }
  6. //这里是保证线程同步
  7. public static synchronized Socket getSocket(String appId) {
  8. return socketPools.get(appId);
  9. }
  10. }

 


 

  1. public class SignUtils {
  2. /**
  3. * <一句话功能简述>
  4. * <功能详细描述>验证返回参数
  5. *
  6. * @param params
  7. * @param key
  8. * @return
  9. * @see [类、类#方法、类#成员]
  10. */
  11. public static boolean checkParam(Map<String, String> params, String key) {
  12. boolean result = false;
  13. if (params.containsKey(“sign”)) {
  14. String sign = params.get(“sign”);
  15. params.remove(“sign”);
  16. StringBuilder buf = new StringBuilder((params.size() + 1) * 10);
  17. SignUtils.buildPayParams(buf, params, false);
  18. String preStr = buf.toString();
  19. String signRecieve = MD5.sign(preStr, “&key=” + key, “utf-8”);
  20. result = sign.equalsIgnoreCase(signRecieve);
  21. }
  22. return result;
  23. }
  24. public static boolean checkRoadGateSign(String params, String key, String sign) {
  25. boolean result = false;
  26. if (params != null && params != “” && params.length() > 0) {
  27. String signRecieve = MD5.sign(params, “&salt=” + key, “utf-8”);
  28. return sign.equalsIgnoreCase(signRecieve);
  29. }
  30. String signRecieve = MD5.sign(“”, “salt=” + key, “utf-8”);
  31. result = sign.equalsIgnoreCase(signRecieve);
  32. return result;
  33. }
  34. /**
  35. * 过滤参数
  36. *
  37. * @param sArray
  38. * @return
  39. * @author
  40. */
  41. public static Map<String, String> paraFilter(Map<String, String> sArray) {
  42. Map<String, String> result = new HashMap<>(sArray.size());
  43. if (sArray.size() <= 0) {
  44. return result;
  45. }
  46. for (String key : sArray.keySet()) {
  47. String value = sArray.get(key);
  48. if (value == null || value.equals(“”) || key.equalsIgnoreCase(“sign”) || key.equalsIgnoreCase(“access_token”)) {
  49. continue;
  50. }
  51. result.put(key, value);
  52. }
  53. return result;
  54. }
  55. /**
  56. * <一句话功能简述>
  57. * <功能详细描述>将map转成String
  58. *
  59. * @param payParams
  60. * @return
  61. * @see [类、类#方法、类#成员]
  62. */
  63. public static String payParamsToString(Map<String, String> payParams) {
  64. return payParamsToString(payParams, false);
  65. }
  66. public static String payParamsToString(Map<String, String> payParams, boolean encoding) {
  67. return payParamsToString(new StringBuilder(), payParams, encoding);
  68. }
  69. /**
  70. * @param payParams
  71. * @return
  72. * @author
  73. */
  74. public static String payParamsToString(StringBuilder sb, Map<String, String> payParams, boolean encoding) {
  75. buildPayParams(sb, payParams, encoding);
  76. return sb.toString();
  77. }
  78. /**
  79. * @param payParams
  80. * @return
  81. * @author
  82. */
  83. public static void buildPayParams(StringBuilder sb, Map<String, String> payParams, boolean encoding) {
  84. List<String> keys = new ArrayList<String>(payParams.keySet());
  85. Collections.sort(keys);
  86. for (String key : keys) {
  87. sb.append(key).append(“=”);
  88. if (encoding) {
  89. sb.append(urlEncode(payParams.get(key)));
  90. } else {
  91. sb.append(payParams.get(key));
  92. }
  93. sb.append(“&”);
  94. }
  95. sb.setLength(sb.length() – 1);
  96. }
  97. public static String urlEncode(String str) {
  98. try {
  99. return URLEncoder.encode(str, “UTF-8”);
  100. } catch (Throwable e) {
  101. return str;
  102. }
  103. }
  104. public static Element readerXml(String body, String encode) throws DocumentException {
  105. SAXReader reader = new SAXReader(false);
  106. InputSource source = new InputSource(new StringReader(body));
  107. source.setEncoding(encode);
  108. Document doc = reader.read(source);
  109. Element element = doc.getRootElement();
  110. return element;
  111. }
  112. public static String sortMapKey(Map<String, String> map) {
  113. List<Map.Entry<String, String>> infoIds = new ArrayList(map.entrySet());
  114. infoIds.sort(Comparator.comparing((o) -> {
  115. return (String) o.getKey();
  116. }));
  117. StringBuilder buf = new StringBuilder();
  118. Iterator var3 = infoIds.iterator();
  119. while (var3.hasNext()) {
  120. Map.Entry<String, String> item = (Map.Entry) var3.next();
  121. if (StringUtils.isNotBlank((CharSequence) item.getKey())) {
  122. String key = (String) item.getKey();
  123. String val = (String) item.getValue();
  124. buf.append(key).append(“=”).append(val);
  125. buf.append(“&”);
  126. }
  127. }
  128. String buff = buf.toString();
  129. if (!buff.isEmpty()) {
  130. buff = buff.substring(0, buff.length() – 1);
  131. }
  132. return buff;
  133. }
}

 

  1. public class MD5 {
  2. /**
  3. * 签名字符串
  4. * @param text 需要签名的字符串
  5. * @param key 密钥
  6. * @param input_charset 编码格式
  7. * @return 签名结果
  8. */
  9. public static String sign(String text, String key, String input_charset) {
  10. text = text + key;
  11. return DigestUtils.md5Hex(getContentBytes(text, input_charset));
  12. }
  13. /**
  14. * 签名字符串
  15. * @param text 需要签名的字符串
  16. * @param sign 签名结果
  17. * @param key 密钥
  18. * @param input_charset 编码格式
  19. * @return 签名结果
  20. */
  21. public static boolean verify(String text, String sign, String key, String input_charset) {
  22. text = text + key;
  23. String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset));
  24. if(mysign.equals(sign)) {
  25. return true;
  26. }
  27. else {
  28. return false;
  29. }
  30. }
  31. /**
  32. * @param content
  33. * @param charset
  34. * @return
  35. * @throws SignatureException
  36. * @throws UnsupportedEncodingException
  37. */
  38. private static byte[] getContentBytes(String content, String charset) {
  39. if (charset == null || “”.equals(charset)) {
  40. return content.getBytes();
  41. }
  42. try {
  43. return content.getBytes(charset);
  44. } catch (UnsupportedEncodingException e) {
  45. throw new RuntimeException(“MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:” + charset);
  46. }
  47. }
  48.  }

转载请注明:我是IT » 自定义serverSocket线程池,处理并发链接

喜欢 (0)or分享 (0)