2. Java Socket

作者: 毛小力 | 来源:发表于2019-07-17 21:15 被阅读0次

    在Java中,套接字实现类为SocketImpl(抽象基类),包含所有的套接字通信方法。
    编程接口为ServerSocket(服务器)和Socket(客户端),内含SocketImpl实例,根据角色调用真正的套接字方法。

    • SocketImpl
    // 创建套接字:流式/数据报
    void create(boolean stream);
    
    // 绑定本地IP地址和端口
    void bind(InetAddress host, int port);
    
    // 监听请求
    void listen(int backlog);
    
    // 请求连接
    void connect(InetAddress address, int port);
    
    // 接受连接
    void accept(SocketImpl s);
    
    // 通过输出流发送消息
    OutputStream getOutputStream();
    void shutdownOutput();
    
    // 通过输入流读取消息
    InputStream getInputStream();
    void shutdownInput();
    
    // 关闭套接字
    void close();
    
    • ServerSocket
    // 创建套接字、绑定本地端口、监听连接请求
    ServerSocket(int port);
    
    // 阻塞直到建立连接
    // 返回:与客户端通信的Socket实例
    Socket accept();
    
    // 关闭套接字
    void close();
    
    • Socket
    // 创建套接字、请求远程套接字,阻塞直到建立连接
    Socket(String host, int port)
    
    // 通过输出流发送消息
    OutputStream getOutputStream();
    // 关闭发送
    void shutdownOutput();
    
    // 通过输入流读取消息
    InputStream getInputStream();
    // 关闭读取
    void shutdownInput();
    
    // 关闭套接字
    void close();
    
    • 示例代码:

      • 服务器:
    int port = 8000;
    ServerSocket serverSocket = null;
    try {
        serverSocket = new ServerSocket(port);
        System.out.println("服务器监听:" + port);
    
        for (int i = 0; i < 3; i++) {
            Socket socket = serverSocket.accept();
            System.out.println("\n服务器建立连接:" +
                    "本地(" + socket.getLocalAddress().getHostAddress() + ":" + socket.getLocalPort() + ")," +
                    "远程(" + socket.getInetAddress().getHostAddress() + ":" + socket.getPort() + ")");
    
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
    
            String line = reader.readLine();
            System.out.println("他:" + line);
    
            line = "你好,我是服务器!\n";
            System.out.print("我:" + line);
            writer.write(line);
            writer.flush();
    
            while (true) {
                line = reader.readLine();
                if (line == null) {
                    break;
                }
                System.out.println("他:" + line);
            }
            socket.shutdownInput();
    
            line = "再见,客户端!\n";
            System.out.print("我:" + line);
            writer.write(line);
            writer.flush();
            socket.shutdownOutput();
    
            socket.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (serverSocket != null) {
            try {
                serverSocket.close();
                System.out.println("\n服务器关闭");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    • 客户端:
    String host = "127.0.0.1";
    int port = 8000;
    Socket socket = null;
    try {
        socket = new Socket();
        socket.connect(new InetSocketAddress(host, port));
        System.out.println("客户端建立连接:" +
                "本地(" + socket.getLocalAddress().getHostAddress() + ":" + socket.getLocalPort() + ")," +
                "远程(" + socket.getInetAddress().getHostAddress() + ":" + socket.getPort() + ")");
    
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
    
        String line = "你好,我是客户端!\n";
        System.out.print("我:" + line);
        writer.write(line);
        writer.flush();
    
        line = reader.readLine();
        System.out.println("他:" + line);
    
        for (int i = 1; i <= 3; i++) {
            line = "第" + i + "句。\n";
            System.out.print("我:" + line);
            writer.write(line);
            writer.flush();
        }
    
        line = "再见,服务器!\n";
        System.out.print("我:" + line);
        writer.write(line);
        writer.flush();
        socket.shutdownOutput();
    
        line = reader.readLine();
        System.out.println("他:" + line);
        socket.shutdownInput();
    
        socket.close();
    
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    相关文章

      网友评论

        本文标题:2. Java Socket

        本文链接:https://www.haomeiwen.com/subject/btcclctx.html