zoukankan      html  css  js  c++  java
  • 最简单的一个socket服务端

    描述:这是一个socket服务端,可以用串口调试工具连接和发送数据过来,服务端启动,客户端可以不断的断开连接、断开连接,不会影响数据接受

    package com.thinkgem.wlw.modules.lhjh.socket.tstandard;
    
    import java.io.BufferedInputStream;
    import java.io.DataInputStream;
    import java.io.IOException;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * socket 服务端
     *
     * @Author: zhouhe
     * @Date: 2019/4/12 11:08
     */
    public class Server {
    
        private static class ClientHandler implements Runnable {
    
            private Socket socket;
    
            public ClientHandler(Socket socket) {
                this.socket = socket;
            }
    
            @Override
            public void run() {
                try {
                    //封装输入流(接收客户端的流)
                    BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
                    DataInputStream dis = new DataInputStream(bis);
    
                    byte[] bytes = new byte[1]; // 一次读取一个byte
    
                    String ret = "";
                    while (dis.read(bytes) != -1) {
                        ret += bytesToHexString(bytes) + "";
                        if (dis.available() == 0) { //一个请求
    
                            //todo 下面打印部分在项目部署的时候要去掉
                         /*   System.out.println(socket.getRemoteSocketAddress() + ":" + ret);
                            System.out.println();
                            System.out.println("转换为字符串后:"+hexStringToString(ret));
                            System.out.println();
                            System.out.println("转为map后的数据:"+aToMap(hexStringToString(ret)));
                            System.out.println();*/
    
    //                        Thread.sleep(3000);
    
    //                        MessageParsing.explain(hexStringToString(ret)); //报文解析
    
                            System.out.println("转换为字符串后:"+hexStringToString(ret));
                            ret = "";
                        }
                    }
                } catch (Exception e) {
    
                } finally {
                    System.out.println("client is over");
                    if (socket != null) {
                        try {
                            socket.close();
                        } catch (IOException e) {
    
                        }
                    }
                }
            }
        }
    
        /**
         * byte[]数组转换为16进制的字符串
         *
         * @param bytes 要转换的字节数组
         * @return 转换后的结果
         */
        public static String bytesToHexString(byte[] bytes) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < bytes.length; i++) {
                String hex = Integer.toHexString(0xFF & bytes[i]);
                if (hex.length() == 1) {
                    sb.append('0');
                }
                sb.append(hex);
            }
            return sb.toString();
        }
    
        /**
         * 16进制转换成为string类型字符串
         * 这个方法中文会乱码,字母和数字都不会乱码
         *
         * @Author zhouhe
         * @param s
         * @return
         */
        public static String hexStringToString(String s) {
            if (s == null || s.equals("")) {
                return null;
            }
            s = s.replace(" ", "");
            byte[] baKeyword = new byte[s.length() / 2];
            for (int i = 0; i < baKeyword.length; i++) {
                try {
                    baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            try {
                s = new String(baKeyword, "UTF-8");
                new String();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            return s;
        }
    
    
        // 字符串转换为 map
        public static Map aToMap(String arr){
            Map map = new HashMap();
            if (null != arr) {
                String[] param = arr.split(";");
                for (int i = 0; i < param.length; i++) {
                    //这里的 index 要 >-1 才是 map格式
                    int index = param[i].indexOf('=');
                    if(index>-1)
                    map.put(param[i].substring(0,index), param[i].substring((index + 1)));
                }
            }
            return map;
        }
    
        /**
         * 启动socketServer
         */
        public static void start(){
            ServerSocket server = null;
            try {
                server = new ServerSocket(8877);
                while (true) {
                    System.out.println("listening...");
    
                    Socket socket = server.accept();
                    System.out.println("连接客户端地址:" + socket.getRemoteSocketAddress());
                    System.out.println("connected...");
                    ClientHandler handler = new ClientHandler(socket);
                    Thread t = new Thread(handler);
                    t.start();
    
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (server != null) {
                    try {
                        server.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    
        //测试方法
        public static void main(String[] args) throws InterruptedException {
         /*   for (int i = 0; i < 100; i++) {
                Thread.sleep(10000);
                System.out.println("测试");
                start();
            }*/
    
    //        MessageParsing.calculation();
            start();
        }
    }

  • 相关阅读:
    浅谈大型网站的SEO策略及如何执行,互联网营销 狼人:
    需求为王,互联网营销 狼人:
    Google推出HTML 5练兵场 提供详尽代码示例,互联网营销 狼人:
    信息架构,互联网营销 狼人:
    产品的成功学,互联网营销 狼人:
    How Digg is Built:讲述Digg背后的技术,互联网营销 狼人:
    网站体验七武器,互联网营销 狼人:
    真正有价值的社交网络——微观下的Twitter,互联网营销 狼人:
    互联网革新的下一个受益者是谁?,互联网营销 狼人:
    Hibernate的hql常用语句整理汇总
  • 原文地址:https://www.cnblogs.com/zhouheblog/p/11658648.html
Copyright © 2011-2022 走看看