public class EchoServer {
public EchoServer(int port) throws IOException {
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("starting echo server on port: " + port);
while (true) {
//监听8888端口,客户端的请求
Socket socket = serverSocket.accept();
System.out.println("accept connection from client");
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
byte[] b = new byte[4 * 1024];
int len;
while ((len = in.read(b)) != -1) {
System.out.println("len="+len);
out.write(b, 0, len);
}
System.out.println("once client request end;closing connection with client");
out.close();
in.close();
socket.close();
}
}
public static void main(String[] args) throws IOException {
new EchoServer(8888);
}
}
java io的类的一些定义:
- inputStream和outputStream是所有流的顶层抽象类。
inputStream水龙头出水的地方,outputStream是所有能接收水的地方。所以inputStream对应的是read方法,outputStream是write方法。 - 这些设备可以是磁盘文件、键盘(输入设备)、显示器(输出设备)、打印机(输出设备)、网络套接字等等
- read(b)方法,会阻塞直到可用,文件到尾段,或者异常。(This method blocks until input data is
available, end of file is detected, or an exception is thrown)
方法返回读取的字节数,返回-1表示没有可读取数据。
inputStream和outputStream参考http://www.cnblogs.com/springcsc/archive/2009/12/03/1616187.html
启动server后,客户端telnet 127.0.0.1 8888测试下。发现长度每次打印的值多2,是流的头部有两位存储长度。
echo 客户端 echo server端log
网友评论