JAVA造轮子之-Socket操做工具类

用java.net.Socket进行Socket操做工具类
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @author JL
 * @version V1.0
 * @Description 用java.net.Socket进行Socket操做工具类
 */
public class SocketUtils {

    private static final String ENCODING = "UTF-8";

    public static void listen(final int port, String content, SocketFunction function) throws IOException{
        ServerSocket serverSocket = null ;
        Socket socket = null;
        try {
            serverSocket = createServer(port);
            socket = createServerSocket(serverSocket);
            //一般获取到socket链接后,都是分配一个线程来处理客户端
            WorkClass workClass = new WorkClass(socket, content, function);
            workClass.work();
        }catch(IOException ioe){
            ioe.printStackTrace();
            throw ioe;
        }finally{
            clientClose(socket);
            //关闭服务端
            serverClose(serverSocket);
        }
    }

    static class WorkClass{
        private Socket socket ;
        private String content;
        private SocketFunction function;
        public WorkClass(Socket socket, String content, SocketFunction function){
            this.socket = socket;
            this.content = content;
            this.function = function;
        }

        public void work() throws IOException {
            String msg = null;
            InputStream in = null;
            OutputStream out = null;
            try {
                in = socket.getInputStream();
                msg = input(in);
                out = socket.getOutputStream();
                output(out, content);
                function.callback(msg);
            }finally{
                //关闭输入输出流
                streamClose(in, out);
            }
        }
    }

    public static void send(String host, int port, String content, SocketFunction function) throws IOException{
        Socket socket = null;
        String msg = null;
        InputStream in = null;
        OutputStream out = null;
        try {
            socket = createClientSocket(host, port);
            out = socket.getOutputStream();
            output(out, content);
            socket.shutdownOutput();//输出完后,须要关闭socket的输出通道,表示不存向服务端输出内容
            in = socket.getInputStream();
            msg = input(in);
            function.callback(msg);
        }catch(UnknownHostException uhe){
            uhe.printStackTrace();
            throw new IOException("主机链接建立异常:" + uhe.getMessage());
        }catch(IOException ioe){
            ioe.printStackTrace();
            throw ioe;
        }finally{
            streamClose(in, out);
            clientClose(socket);
        }
    }

    public static void streamClose(InputStream in, OutputStream out){
        //IOUtils.closeQuietly(in); 可用IOUtils工具类关闭流
        if (in != null){
            try {
                in.close();
            }catch(IOException ioe){
                System.out.println("关闭输入流异常:" + ioe.getMessage());
            }
        }
        if (out != null){
            try {
                out.flush();
                out.close();
            }catch(IOException ioe){
                System.out.println("关闭输出流异常:" + ioe.getMessage());
            }
        }
    }

    private static ServerSocket createServer(int port) throws IOException {
        System.out.println("监听端口号:" + port);
        return new ServerSocket(port);
    }

    private static Socket createServerSocket(ServerSocket serverSocket) throws IOException {
        Socket socket = serverSocket.accept();
        System.out.println("获取到客户端链接:" + socket.getInetAddress().getHostAddress());
        return socket;
    }

    private static Socket createClientSocket(String host, int port) throws UnknownHostException, IOException {
        return new Socket(host, port);
    }

    private static void serverClose(ServerSocket server) {
        if (server != null && !server.isClosed()){
            try{
                server.close();
            }catch(IOException ioe){
                System.out.println("服务关闭异常:" + ioe.getMessage());
            }
        }
    }

    private static void clientClose(Socket socket){
        if (socket != null && !socket.isClosed()){
            try{
                socket.close();
            }catch(IOException ioe){
                System.out.println("Socket关闭异常:" + ioe.getMessage());
            }
        }
    }

    public static OutputStream output(OutputStream out, String content) throws IOException {
        try{
            out.write(content.getBytes(ENCODING));
        }finally{
            return out;
        }
    }

    public static String input(InputStream in) throws IOException {
        int len;
        char[] b = new char[1024];
        StringBuilder sb = new StringBuilder();
        BufferedReader reader ;
        try {
            //以字符流为主,如需字节流,则不须要BufferedReader和InputStreamReader,能够直接从InputStream中获取或采用对应缓冲包装类
            reader = new BufferedReader(new InputStreamReader(in, ENCODING));
            while ((len = reader.read(b)) != -1) {
                sb.append(b, 0, len);
            }
            //reader.close();
        }finally{
        }
        return sb.toString();
    }

    public interface SocketFunction{
        void callback(String msg);
    }

    public static void main(String[] args) throws IOException{
        String data = "这是测试数据:";
        //测试时,请分别单独启动send和listen方法
        //客户端
//        send("127.0.0.1",8111, "this is client test", new SocketFunction(){
//            @Override
//            public void callback(String msg) {
//                System.out.println(data + msg);
//            }
//        });

        //服务端
        listen(8111, "this is server test", new SocketFunction() {
            @Override
            public void callback(String msg) {
                System.out.println(data + msg);
            }
        });
    }

}

 

说明:java

作过项目的人都知道,不少写过的可重复利用的代码块或有用的工具类没有怎么整理,当须要的时候,又得打开项目查找一翻,虽然功能开发不难,可是又得花时间成本去写去测试,这样的重复造轮子的事情太屡次了;所以不如把轮子保留,供你们一块儿使用;app

1.这个轮子能够有:须要使用的时候确实还不存在这个组件。
2.我须要的时候轮子不在:每一种技术或工具产生都有它的项目背景,当代码写在项目里的时候,我知道有这个东西,当换了一个项目或公司后,没有备份也没有记录,这个时候你不在了,又得花时间手打一遍;
3.我不知道是否是造轮子:大多数状况下初学者很难分清楚本身是否是在重复造轮子,事实上造轮子不是我目的。个人目的是完成工做任务,任务完成的速度越快越好,质量越高越好。而不是去判断本身在不在造轮子。
4.不想重复花时间造轮子:有时候还会碰到一些并不困难可是很占时间的东西,固然有现成的轮子是花时间最少的;
5.我就是想学习轮子:初学者的并非在重复造轮子,而是学习后以提升为本身的知识与技能。socket

轮子有过测试,但不免有失误,若有错误处,还敬请指出;ide

相关文章
相关标签/搜索