BIO的简单Demo
package jesse.test1; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.Executor; import java.util.concurrent.Executors; public class DemoServer extends Thread{ private ServerSocket serverSocket; public int getPort(){ return serverSocket.getLocalPort(); } public void run(){ try { serverSocket = new ServerSocket(0); //使用多线程实现 Executor executor = Executors.newFixedThreadPool(8); while(true){ Socket socket = serverSocket.accept(); RequestHandler requestHandler = new RequestHandler(socket); /*requestHandler.start();*/ executor.execute(requestHandler); } } catch (IOException e) { e.printStackTrace(); }finally{ if(serverSocket != null){ try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static void main(String[] args) { DemoServer server = new DemoServer(); server.start(); try { Socket client = new Socket(InetAddress.getLocalHost(), server.getPort()); BufferedReader bufferReader = new BufferedReader(new InputStreamReader(client.getInputStream())); System.out.println(bufferReader.readLine()); } catch (IOException e) { e.printStackTrace(); } } } /** * 1、服务端ServerSocket,启动绑定端口 * 2、调用accept,阻塞等待客户端连接 * 3、客户端连接后,启动一个单独线程负责处理客户端请求 * * 也可以使用多线程来处理连接不是很多的情况 */ class RequestHandler extends Thread{ private Socket socket; public RequestHandler(Socket socket) { this.socket = socket; } @Override public void run(){ try { PrintWriter out = new PrintWriter(socket.getOutputStream()); out.println("Hello World"); out.flush(); } catch (IOException e) { e.printStackTrace(); } } }