Java Tutorials-08-网络编程API

Server/Client的Socket API介绍.

Server

ServerSocket server = new ServerSocket(9090);
Socket client = server.accept(); // 阻塞
InputStream input = client.getInputStream();
OutputStream output = client.getOutputStream();

double value = input.readDouble();
output.writeDouble(value);

inpput.close();
output.close();
server.close();

Client

/* 方式1 */
Socket socket = new Socket(host, port); // 阻塞
OutputStream out = socket.getOutputStream();
...
out.close();
socket.close();

/* 方式2 */
Socket socket = new Socket();
socket.connect(new InetSocketAddress(host, port), timeout); // 阻塞

半关闭

  • Socket.shutdownOutput():
  • Socket.shutdownInput():
  • boolean isOutputShutdown():
  • boolean isInputShutdown():
Socket socket = new Socket(host, port);
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();

// 向out写入一些数据, 写入完毕, 半关闭socket的输出
socket.shutdownOutput();
// 此时socket仍可以从InputStream读取, 直到shutdown...
socket.shutdown();

shutdownOutput 实际是发送了 FIN 报文给对方,意思是己方不再发送数据 [[../22.Network-Protocol/网络协议2-TCP#三次握手、四次挥手]]

可中断套接字

当连接到一个套接字时,当前线程将会被阻塞直到建立连接或产生超时为止。java.nio包提供的一个特性——SocketChannel类,与上面的Socket不同,SocketChannel是可以中断的
如果发生中断, 下面的操作不会阻塞, 而是抛出异常

SocketChannel channel = SocketChannel.open();
channel.socket().connect(new InetSocketAddress("localhost", 8080));
Scanner in = new Scanner(channel);
while (!Thread.currentThread().isInterrupted())
{
if (in.hasNextLine())
String line = in.nextLine();
}

KeepAlive

参考: [[../22.Network-Protocol/网络协议2a-TCP的KeepAlive]]