socket 服务端编写之BIO网络学习
JavaSocket服务端demo开发
1 package com.example.demo.bio; 2 3 import java.io.IOException; 4 import java.net.ServerSocket; 5 import java.net.Socket; 6 7 /** 8 * @Author: Lambert 9 * @Date: 2019-01-07 00:3710 * @Description:11 */12 public class BioServer {13 private static final int PORT = 8080;14 15 public static void main(String[] args) throws IOException {16 17 ServerSocket serverSocket = null;18 try {19 serverSocket = new ServerSocket(PORT);20 System.out.println("the time server is start in port" + PORT);21 22 Socket socket = null;23 while (true) {24 //阻塞项目25 socket = serverSocket.accept();26 new Thread(new TimeServerHandler(socket)).start();27 }28 } catch (29 Exception e) {30 e.printStackTrace();31 } finally {32 {33 if (serverSocket != null) {34 System.out.println("the time server close");35 serverSocket.close();36 }37 38 }39 }40 41 }42 }
1 package com.example.demo.bio; 2 3 import java.io.BufferedReader; 4 import java.io.InputStreamReader; 5 import java.io.PrintWriter; 6 import java.net.Socket; 7 import java.util.Date; 8 9 /**10 * @Author: Lambert11 * @Date: 2019-01-07 00:5612 * @Description:13 */14 public class TimeServerHandler implements Runnable {15 16 private Socket socket;17 18 /**19 * 构造函数20 *21 * @param socket22 */23 public TimeServerHandler(Socket socket) {24 this.socket = socket;25 }26 27 @Override28 public void run() {29 BufferedReader in = null;30 PrintWriter out = null;31 try {32 //获得输入流33 in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));34 out = new PrintWriter(this.socket.getOutputStream(), true);35 36 String body = null;37 while ((body = in.readLine()) != null && body.length() != 0) {38 System.out.println("the time Server receive msg:" + body);39 out.println(new Date().toString());40 //暂时不需要41 // out.flush();42 }43 44 } catch (Exception e) {45 e.printStackTrace();46 } finally {47 if (in != null) {48 try {49 in.close();50 } catch (Exception e) {51 e.printStackTrace();52 }53 }54 if (out != null) {55 try {56 out.close();57 } catch (Exception e) {58 e.printStackTrace();59 }60 }61 if (socket != null) {62 try {63 this.socket.close();64 } catch (Exception e) {65 e.printStackTrace();66 }67 }68 }69 70 71 }72 73 }
测试
使用curl 请求本地8080端口,会有4次请求