大橙子网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
这篇文章给大家介绍在java项目中使用 Socket如何实现模拟一个HTTP服务器,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
创新互联是一家集网站建设,彰武企业网站建设,彰武品牌网站建设,网站定制,彰武网站建设报价,网络营销,网络优化,彰武网站推广为一体的创新建站企业,帮助传统企业提升企业形象加强企业竞争力。可充分满足这一群体相比中小企业更为丰富、高端、多元的互联网需求。同时我们时刻保持专业、时尚、前沿,时刻以成就客户成长自我,坚持不断学习、思考、沉淀、净化自己,让我们为更多的企业打造出实用型网站。HTTP基于TCP协议,协议采用了请求/响应模型。客户端向服务器发送一个请求,请求头包含请求的方法、URL、协议版本、以及包含请求修饰符、客户信息和内容的类似于MIME的消息结构。服务器以一个状态行作为响应,响应的内容包括消息协议的版本,成功或者错误编码加上包含服务器信息、实体元信息以及可能的实体内容
具体字段这里不作解释,不懂的请先自己了解http协议。这里主要是根据请求响应这一过程模拟HTTP服务器。
下面是代码:
package com.example.httpserver; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class HttpServer { private static final Integer port = 80;//HTTP默认端口80 public static void main(String[] args) { ServerSocket serverSocket; try { //建立服务器Socket,监听客户端请求 serverSocket = new ServerSocket(port); System.out.println("Server is running on port:"+serverSocket.getLocalPort()); //死循环不间断监听客户端请求 while(true){ final Socket socket = serverSocket.accept(); System.out.println("biuld a new tcp link with client,the cient address:"+ socket.getInetAddress()+":"+socket.getPort()); //并发处理HTTP客户端请求 service(socket); } } catch (IOException e) { e.printStackTrace(); } } public static void service(Socket socket) { new Thread(){ public void run(){ InputStream inSocket; try { //获取HTTP请求头 inSocket = socket.getInputStream(); int size = inSocket.available(); byte[] buffer = new byte[size]; inSocket.read(buffer); String request = new String(buffer); System.out.println("ClientBrowser:\n"+request+"\n" + "------------------------------------------------------------------"); String firstLineOfRequest = ""; String[] heads; String uri = "/index.html"; String contentType =""; if(request.length() > 0){ firstLineOfRequest = request.substring(0,request.indexOf("\r\n")); heads = firstLineOfRequest.split(" "); uri = heads[1]; if(uri.indexOf("html") != -1){ contentType = "text/html"; }else{ contentType = "application/octet-stream"; } } //将响应头发送给客户端 String responseFirstLine = "HTTP/1.1 200 OK\r\n"; String responseHead = "Content-Type:" + contentType +"\r\n"; OutputStream outSocket = socket.getOutputStream(); System.out.println("ServerResponse:\n"+responseFirstLine+"\n"+responseHead+"\n" + "--------------------------------------------------------------------"); outSocket.write(responseFirstLine.getBytes()); outSocket.write(responseHead.getBytes()); //通过HTTP请求中的uri读取相应文件发送给客户端 FileInputStream writehtml = new FileInputStream(new File("wwwroot"+uri)); outSocket.write("\r\n".getBytes()); byte[] htmlbuffer = new byte[writehtml.available()]; if(writehtml !=null){ int len = 0; System.out.println("writeHtml"); while((len = writehtml.read(htmlbuffer)) != -1){ outSocket.write(htmlbuffer, 0,len); } } outSocket.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } }.start(); } }