Java 网络编程

Socket 编程模型、ServerSocket 与 Socket、InetAddress 的用法。

Intermediate
Key Points服务端用 ServerSocket.accept() 阻塞等待连接,客户端用 new Socket(host, port) 发起连接,双方通过输入输出流通信。

Socket 编程

The TCP model: the server binds a ServerSocket and blocks in accept(); the client connects with a Socket, then both sides exchange data through InputStream / OutputStream.

Java
// 服务端骨架
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws Exception {
        try (ServerSocket server = new ServerSocket(9000)) {
            System.out.println("listening on 9000");
            try (Socket s = server.accept();
                 PrintWriter out = new PrintWriter(s.getOutputStream(), true)) {
                out.println("hello client");
            }
        }
    }
}
Output
listening on 9000

Socket 客户端

The client calls new Socket(host, port); streams then behave like file streams. A failed connect throws ConnectException, and a closed peer yields -1 or an exception.

Java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;

public class Client {
    public static void main(String[] args) throws Exception {
        try (Socket s = new Socket("127.0.0.1", 9000);
             BufferedReader in = new BufferedReader(
                     new InputStreamReader(s.getInputStream()))) {
            System.out.println(in.readLine());
        }
    }
}
Output
hello client
The client needs the server running first. Run alone it throws ConnectException: Connection refused — expected, since no connection exists.

InetAddress 类

InetAddress represents an IP address: getByName resolves a host, getLocalHost returns this machine, and getHostName / getHostAddress give the name and IP text.

Java
import java.net.InetAddress;

public class AddressDemo {
    public static void main(String[] args) throws Exception {
        InetAddress local = InetAddress.getLocalHost();

        System.out.println(local.isLoopbackAddress() || !local.isLoopbackAddress());
        System.out.println(local.getHostAddress().length() > 0);

        InetAddress loop = InetAddress.getByName("127.0.0.1");
        System.out.println(loop.isLoopbackAddress());
        System.out.println(loop.getHostAddress());
    }
}
Output
true
true
true
127.0.0.1

Friends & Partners