已经两天没更过教程了,今天也不更(;′⌒`),这期来分享一下我自己写的Java ServerSocket服务器和客户端类,都提供了数据接收接口,即写即用,也加入了自动结束监听线程,解决了随运行时间增加导致高CPU占用的问题。下面就直接分享代码,不做过多的解释了。

public class SocketX {
    private static String mess = null;

    // Usage:
    // ServerSocket serverSocket = new ServerSocket(23333);
    // while (!serverSocket.isClosed()) {
    //     while (true) {
    //         Socket client;
    //         client = serverSocket.accept();
    //         SocketX.SocketServerThread socketServerThread = new SocketX.SocketServerThread(client);
    //         socketServerThread.setSocketServerHandle(receivedMsg -> {
    //             System.out.println(""+receivedMsg);
    //         }
    //      }
    // }

    // Socket socket = new Socket("127.0.0.1",23333);
    // sendMsg(socket,"123");

    public static class SocketClientThread implements Runnable {
        public Socket socket;
        public InputStream inputStream;
        public SocketClientHandle socketClientHandle;
        public SocketClientThread(Socket socket) {
            this.socket = socket;
            try {
                this.inputStream = socket.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public interface SocketClientHandle {
            void onMsgReceived(String receivedMsg);
        }

        public void setSocketClientHandle(SocketClientHandle socketClientHandle) {
            this.socketClientHandle = socketClientHandle;
        }

        @Override
        public void run() {
            try {
                while (inputStream != null) {
                    byte[] buf = new byte[64*1024];
                    int len = 0;
                    String msg;
                    while ((len = inputStream.read(buf)) != -1) {
                        msg = new String(buf, 0, len);
                        socketClientHandle.onMsgReceived(URLDecoder.decode(msg,"UTF-8"));
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static class SocketServerThread implements Runnable {
        private Socket socket;
        private String receivedMsg = "";

        private SocketServerHandle socketServerHandle;

        public interface SocketServerHandle {
            void onMsgReceive(String receivedMsg) throws InvocationTargetException, IllegalAccessException, UnsupportedEncodingException;
        }

        public SocketServerThread(Socket socket) {
            this.socket = socket;
        }

        public void setSocketServerHandle(SocketServerHandle socketServerHandle) {
            this.socketServerHandle = socketServerHandle;
        }

        public InputStream is;
        @Override
        public void run() {
            //BufferedReader is = null;
            while (true) {
                try {
                    is = socket.getInputStream();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (is != null) {
                    //while (is.available() != 0) {
                    byte[] bytes = new byte[64*1024];
                    try {
                        is.read(bytes);
                    } catch (IOException e) {
                        try {
                            socket.sendUrgentData(0xFF);
                        } catch (Exception e2) {
                            try {
                                socket.close();
                            } catch (IOException ioException) {
                                ioException.printStackTrace();
                            }
                            Thread.yield();
                            break;
                        }
                        e.printStackTrace();
                    }
                    try {
                        String string = new String(bytes);
                        if (!string.equalsIgnoreCase("")) {
                            string = string.replace("eof", "");
                            String[] sp = string.split("\\|");
                            for (int i = 0; i < sp.length; i++) {
                                if (i == sp.length - 1) {
                                    break;
                                }
                                socketServerHandle.onMsgReceive(URLDecoder.decode(sp[i], "UTF-8"));
                            }
                        }
                    } catch (IllegalAccessException | UnsupportedEncodingException | InvocationTargetException e) {
                        e.printStackTrace();
                    }
                    //}
                }
            }


        }
    }



    public static String read(Socket socket) {
        InputStream is = null;
        BufferedReader br = null;
        try {
            is = socket.getInputStream();
            br = new BufferedReader(new InputStreamReader(is));
            mess = br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return mess;
    }

    public static void sendMsg(Socket socket, String msg) {
        OutputStream os = null;
        msg += "|";
        try {
            os = socket.getOutputStream();
            os.write(msg.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void sendMsg(Socket socket, String msg, Encryptions.EncryptionsType encryptionsType) {
        try {
            switch (encryptionsType) {
                case URLCODE:
                    sendMsg(socket, URLEncoder.encode(msg,"UTF-8"));
                    break;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}

类的用法在开头Usage已给出服务端的范例,客户端同理。

防止CPU占用过高:将SocketX.SocketServerThread对象储存在列表中,定期结束线程。

分类: Java开发

0 条评论

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注