千家信息网

JAVA中怎么实现一个Socket操作工具类

发表于:2024-09-25 作者:千家信息网编辑
千家信息网最后更新 2024年09月25日,JAVA中怎么实现一个Socket操作工具类,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。用java.net.Socke
千家信息网最后更新 2024年09月25日JAVA中怎么实现一个Socket操作工具类

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);            }        });    }}

说明:

做过项目的人都知道,很多写过的可重复利用的代码块或有用的工具类没有怎么整理,当需要的时候,又得打开项目查找一翻,虽然功能开发不难,但是又得花时间成本去写去测试,这样的重复造轮子的事情太多次了;因此不如把轮子保留,供大家一起使用;

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

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注行业资讯频道,感谢您对的支持。

0