收藏文章 楼主

最简单的一个socket服务端

版块:linux   类型:普通   作者:小绿叶技术博客   查看:544   回复:0   获赞:0   时间:2021-09-03 11:51:17

最简单的一个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();

    }

}



参考资料:https://www.cnblogs.com/zhouheblog/p/11658648.html

提供企业建站服务,免费网防系统,提交信息登录 http://yundun.ddoss.cn 邮箱: proposal@ddoss.cn 
回复列表
默认   热门   正序   倒序

回复:最简单的一个socket服务端

头像

用户名:

粉丝数:

签名:

资料 关注 好友 消息