套接字可以与NIO通道一起使用吗?

时间:2019-07-08 11:08:45

标签: java sockets network-programming

我有一个示例,其中我将Socket与经典Java IO流API一起使用。 我知道会有类似的SocketChannel退出。但为澄清起见,我想知道Socket是否可以与频道一起使用。

当我尝试socket.getChannel()时,它返回了null

package com.zetcode;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketHeadRequest {

    public static void main(String[] args) {

        var hostname = "example.com";
        int port = 80;

        try (Socket socket = new Socket(hostname, port)) {

            try (var writer = new PrintWriter(socket.getOutputStream(), true)) {

                writer.println("HEAD / HTTP/1.1");
                writer.println("Host: " + hostname);
                writer.println("User-Agent: Console Http Client");
                writer.println("Accept: text/html");
                writer.println("Accept-Language: en-US");
                writer.println("Connection: close");
                writer.println();

                try (var reader = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
                    String line;

                    while ((line = reader.readLine()) != null) {
                        System.out.println(line);
                    }
                }
            }
        } catch (UnknownHostException ex) {

            System.out.println("Server not found: " + ex.getMessage());

        } catch (IOException ex) {

            System.out.println("I/O error: " + ex.getMessage());
        }
    }
}

0 个答案:

没有答案