溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

JAVA中怎么實(shí)現(xiàn)一個(gè)Socket操作工具類(lèi)

發(fā)布時(shí)間:2021-06-18 14:56:29 來(lái)源:億速云 閱讀:703 作者:Leah 欄目:大數(shù)據(jù)

JAVA中怎么實(shí)現(xiàn)一個(gè)Socket操作工具類(lèi),很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來(lái)學(xué)習(xí)下,希望你能有所收獲。

用java.net.Socket進(jìn)行Socket操作工具類(lèi)
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @author JL
 * @version V1.0
 * @Description 用java.net.Socket進(jìn)行Socket操作工具類(lèi)
 */
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連接后,都是分配一個(gè)線程來(lái)處理客戶(hù)端
            WorkClass workClass = new WorkClass(socket, content, function);
            workClass.work();
        }catch(IOException ioe){
            ioe.printStackTrace();
            throw ioe;
        }finally{
            clientClose(socket);
            //關(guān)閉服務(wù)端
            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{
                //關(guān)閉輸入輸出流
                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();//輸出完后,需要關(guān)閉socket的輸出通道,表示不存向服務(wù)端輸出內(nèi)容
            in = socket.getInputStream();
            msg = input(in);
            function.callback(msg);
        }catch(UnknownHostException uhe){
            uhe.printStackTrace();
            throw new IOException("主機(jī)連接創(chuàng)建異常:" + 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工具類(lèi)關(guān)閉流
        if (in != null){
            try {
                in.close();
            }catch(IOException ioe){
                System.out.println("關(guān)閉輸入流異常:" + ioe.getMessage());
            }
        }
        if (out != null){
            try {
                out.flush();
                out.close();
            }catch(IOException ioe){
                System.out.println("關(guān)閉輸出流異常:" + ioe.getMessage());
            }
        }
    }

    private static ServerSocket createServer(int port) throws IOException {
        System.out.println("監(jiān)聽(tīng)端口號(hào):" + port);
        return new ServerSocket(port);
    }

    private static Socket createServerSocket(ServerSocket serverSocket) throws IOException {
        Socket socket = serverSocket.accept();
        System.out.println("獲取到客戶(hù)端連接:" + 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("服務(wù)關(guān)閉異常:" + ioe.getMessage());
            }
        }
    }

    private static void clientClose(Socket socket){
        if (socket != null && !socket.isClosed()){
            try{
                socket.close();
            }catch(IOException ioe){
                System.out.println("Socket關(guān)閉異常:" + 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 {
            //以字符流為主,如需字節(jié)流,則不需要BufferedReader和InputStreamReader,可以直接從InputStream中獲取或采用對(duì)應(yīng)緩沖包裝類(lèi)
            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 = "這是測(cè)試數(shù)據(jù):";
        //測(cè)試時(shí),請(qǐng)分別單獨(dú)啟動(dòng)send和listen方法
        //客戶(hù)端
//        send("127.0.0.1",8111, "this is client test", new SocketFunction(){
//            @Override
//            public void callback(String msg) {
//                System.out.println(data + msg);
//            }
//        });

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

}

說(shuō)明:

做過(guò)項(xiàng)目的人都知道,很多寫(xiě)過(guò)的可重復(fù)利用的代碼塊或有用的工具類(lèi)沒(méi)有怎么整理,當(dāng)需要的時(shí)候,又得打開(kāi)項(xiàng)目查找一翻,雖然功能開(kāi)發(fā)不難,但是又得花時(shí)間成本去寫(xiě)去測(cè)試,這樣的重復(fù)造輪子的事情太多次了;因此不如把輪子保留,供大家一起使用;

1.這個(gè)輪子可以有:需要使用的時(shí)候確實(shí)還不存在這個(gè)組件。
2.我需要的時(shí)候輪子不在:每一種技術(shù)或工具產(chǎn)生都有它的項(xiàng)目背景,當(dāng)代碼寫(xiě)在項(xiàng)目里的時(shí)候,我知道有這個(gè)東西,當(dāng)換了一個(gè)項(xiàng)目或公司后,沒(méi)有備份也沒(méi)有記錄,這個(gè)時(shí)候你不在了,又得花時(shí)間手打一遍;
3.我不知道是不是造輪子:大多數(shù)情況下初學(xué)者很難分清楚自己是不是在重復(fù)造輪子,事實(shí)上造輪子不是我目的。我的目的是完成工作任務(wù),任務(wù)完成的速度越快越好,質(zhì)量越高越好。而不是去判斷自己在不在造輪子。
4.不想重復(fù)花時(shí)間造輪子:有時(shí)候還會(huì)碰到一些并不困難但是很占時(shí)間的東西,當(dāng)然有現(xiàn)成的輪子是花時(shí)間最少的;
5.我就是想學(xué)習(xí)輪子:初學(xué)者的并不是在重復(fù)造輪子,而是學(xué)習(xí)后以提高為自己的知識(shí)與技能。

看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝您對(duì)億速云的支持。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI