1、BIO
BIO为阻塞式IO,tomcat7以前采用的是BIO。服务器实现模式为一个连接一个线程,即客户端有连接请求时服务器端就需要启动一个线程进行处理,但可以通过线程池改善。
服务端:
public static void main(String[] args) throws Exception {
// 创建serverSocket对象
ServerSocket serverSocket = new ServerSocket(9999);
while(true){
//监听客户端
Socket accept = serverSocket.accept();//阻塞
//从连接中去取出输入流来接收信息
InputStream inputStream = accept.getInputStream();//阻塞
byte[] bytes = new byte[10];
inputStream.read(bytes);
String hostAddress = accept.getInetAddress().getHostAddress();
System.out.println(hostAddress + ":" + new String(bytes).trim());
//从连接中取出输出流并回话
OutputStream outputStream = accept.getOutputStream();
outputStream.write("收到信息".getBytes());
//关闭
accept.close();
}
}
客户端:
public static void main(String[] args) throws IOException {
//创建socket对象
Socket socket = new Socket("127.0.0.1",9999);
//从连接中取出输出流
OutputStream outputStream = socket.getOutputStream();
System.out.println("请输入:");
Scanner scanner = new Scanner(System.in);
String msg = scanner.nextLine();
outputStream.write(msg.getBytes());
//从连接中取出输入流
InputStream inputStream = socket.getInputStream();//阻塞
byte[] b = new byte[20];
inputStream.read(b);
System.out.println("服务端响应:" + new String(b).trim());
//关闭
socket.close();
}