Socket API使用——模拟http协议
简单的c/s程序——服务端实例
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SocketServer {public static void main(String[] args) throws Exception {ServerSocket serverSocket=new ServerSocket(8080);System.out.println("tomcat 服务器启动成功");ExecutorService threadPool = Executors.newFixedThreadPool(3);while (!serverSocket.isClosed()){Socket request=serverSocket.accept();threadPool.execute(()->{try {InputStream inputStream=request.getInputStream();System.out.println("收到请求");BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));String msg=null;while ((msg=reader.readLine())!=null){if(msg.length()==0){break;}System.out.println(msg);}System.out.println("----------------end");} catch (IOException e) {throw new RuntimeException(e);}});}}
}
这是一个简单的c/s架构的程序如果直接通过浏览器进行访问会出现如下情况
控制台输出如下信息
因为缺少访问的协议,所以访问时浏览器不能正常访问
那么我们先从http协议看起
http协议——请求数据包解析
http协议——响应数据包解析
简单模拟http服务
通过对数据包的解析,我们就可以通过服务端进行模拟响应结果
首先是需要填写响应的协议的版本号和状态码
http/1.1 200 OK
然后是响应给客户端的长度
Content-length: 11
最后是响应的内容如:
hello world
实现
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;public class SocketServer {public static void main(String[] args) throws Exception {ServerSocket serverSocket=new ServerSocket(8080);System.out.println("tomcat 服务器启动成功");ExecutorService threadPool = Executors.newFixedThreadPool(3);while (!serverSocket.isClosed()){Socket request=serverSocket.accept();threadPool.execute(()->{try {InputStream inputStream=request.getInputStream();System.out.println("收到请求");BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));String msg=null;while ((msg=reader.readLine())!=null){if(msg.length()==0){break;}System.out.println(msg);}System.out.println("----------------end");//接收数据后模拟http返回结果OutputStream outputStream=request.getOutputStream();outputStream.write("HTTP/1.1 200 OK\r\n".getBytes());outputStream.write("Content-Length: 11\r\n\r\n".getBytes());//响应内容outputStream.write("hello world".getBytes());outputStream.flush();} catch (IOException e) {throw new RuntimeException(e);}});}}
}
响应成功