客户端通过new Socket()方法来创建Socket对象,服务器通过new serverSocket来创建TCP对象,通过accept()方法接受客户端的请求,并返回一个对象
服务器端通过new ServerSocket()创建通信的Socket对象
创建是在accept()中实现的
public Socket accept() throws IOException {
if (isClosed())
throw new SocketException("Socket is closed");
if (!isBound())
throw new SocketException("Socket is not bound yet");
Socket s = new Socket((SocketImpl) null);
implAccept(s);
return s;
}
另外,创建ServerSocket有两种方式,第一种无参构造函数是未绑定的,还需要进一步绑定端口才能accept.
```
public static void main(String[] args) throws Exception{
ServerSocket serverSocket = new ServerSocket();
serverSocket.bind(new InetSocketAddress(8081));
ServerSocket serverSocket1 = new ServerSocket(8081);
serverSocket.accept();
}
```
网友评论