搭建虚拟服务器环境&服务器开线程响应请求
搭建虚拟服务器环境
创建项目

package web; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class MyHttpServer { private static int count = 1; public static void main(String[] args) throws IOException { ServerSocket server = new ServerSocket(8080); System.out.println("服务器已经启动,监听端口在8080..."); while (true) { Socket socket = server.accept(); InputStream is = socket.getInputStream(); OutputStream os = socket.getOutputStream(); byte[] buf = new byte[1024*1024]; int len = is.read(buf); System.out.println("读到的字节数量:" + len); String s = new String(buf, 0, len); System.out.println(s); os.write("HTTP/1.1 200 OK\r\n".getBytes()); os.write("Content-Type: text/plain\r\n".getBytes()); os.write("\r\n".getBytes()); os.write((" "+count).getBytes()); count++; os.flush(); socket.close(); } } }
浏览器访问localhost:8080


服务器开线程响应请求
package web; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class MyHttpServer { private static int count = 1; public static void main(String[] args) throws IOException { ServerSocket server = new ServerSocket(8080); System.out.println("服务器已经启动,监听端口在8080..."); while (true) { Socket socket = server.accept(); InputStream is = socket.getInputStream(); OutputStream os = socket.getOutputStream(); byte[] buf = new byte[1024*1024]; new Thread(new Runnable() { @Override public void run() { int len = 0; try { len = is.read(buf); if (len == -1) return; System.out.println("读到的字节数量:" + len); String s = new String(buf, 0, len); System.out.println(s); os.write("HTTP/1.1 200 OK\r\n".getBytes()); os.write("Content-Type: text/plain\r\n".getBytes()); os.write("\r\n".getBytes()); os.write((" "+count).getBytes()); count++; os.flush(); } catch (IOException e) { throw new RuntimeException(e); }finally { if (socket != null){ try { socket.close(); } catch (IOException e) { throw new RuntimeException(e); } } } } }).start(); } } }



浙公网安备 33010602011771号