ServerSocket java源码解析
时间: 2024-05-22 09:15:12 浏览: 135
ServerSocket是Java提供的用于监听客户端连接请求的类,其源码解析如下:
1. ServerSocket类的定义:
public class ServerSocket implements java.io.Closeable {
...
}
2. 构造方法:
public ServerSocket(int port) throws IOException {
...
}
public ServerSocket(int port, int backlog) throws IOException {
...
}
public ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException {
...
}
3. accept()方法:
public Socket accept() throws IOException {
...
}
4. close()方法:
public void close() throws IOException {
...
}
5. setSoTimeout()方法:
public void setSoTimeout(int timeout) throws SocketException {
...
}
6. getLocalSocketAddress()方法:
public SocketAddress getLocalSocketAddress() {
...
}
7. getInetAddress()方法:
public InetAddress getInetAddress() {
...
}
8. getLocalPort()方法:
public int getLocalPort() {
...
}
9. getReceiveBufferSize()方法:
public int getReceiveBufferSize() throws SocketException {
...
}
10. setReceiveBufferSize()方法:
public void setReceiveBufferSize(int size) throws SocketException {
...
}
11. getSoTimeout()方法:
public int getSoTimeout() throws IOException {
...
}
12. setReuseAddress()方法:
public void setReuseAddress(boolean on) throws SocketException {
...
}
13. isBound()方法:
public boolean isBound() {
...
}
14. isClosed()方法:
public boolean isClosed() {
...
}
15. bind()方法:
public void bind(SocketAddress bindpoint) throws IOException {
...
}
16. getChannel()方法:
public ServerSocketChannel getChannel() {
...
}
以上是ServerSocket类的主要方法和属性,其实现原理是通过底层操作系统的socket接口实现的。当ServerSocket对象调用accept()方法时,会阻塞等待客户端的连接请求,并返回一个Socket对象用于与客户端进行通信。当ServerSocket对象调用close()方法时,会关闭ServerSocket及其对应的底层socket资源。其他方法均为一些与底层socket相关的操作,例如设置超时时间、获取本地地址等。
阅读全文