一、ServerSocket类
ServerSocket对象用于监听来自客户端的Socket连接,如果没有连接,它将一直处于等待状态,在新建这个类的时候可以指定监听的端口。
Socket accept() 调用ServerSocket对象的accept()方法,可以返回监听到的Socket对象。
使用以下代码可以通过循环不断调用accept()方法。
ServerSockrt ss = new ServerSocket(30000); while(true){ Socket s = ss.accept(); //使用Socket的代码 }
二、Socket类
通过new Socket()的方法可以建立与远程主机的TCP连接,该构造器有两个参数,第一个是目标主机的IP地址,第二个是端口,如下列代码建立了与本地的30000端口的连接。
Socket s = new Socket("127.0.0.1 ",30000);
通过Socket的getInputream()和getOutputStream()方法可以获得Socket的输入流和输出流,用于完成BIO模式的网络IO。
Socket使用完成后,调用Socket的实例的close()方法关闭Socket。
SetSoTimeout()方法来设置Socket连接的Timeout时长。超时则会引发SocketTimeoutException异常
三、半关闭的Socket
前面介绍的close()方法将会关闭Socket连接,所以必须在Socket再也不会使用时调用。
shutdownInput()方法,关闭该Socket的输入流,;shutdownOutput()方法,关闭该Socket的输出流。这种半关闭的Socket被用于Http这种短连接的请求。
当服务器接受到一个http请求时,再接收完http请求包后关闭了Socket的输出流,返回respond后再关闭这次Socket的输入流。