<h3>最近复习计算机网络,复习完应用层之后对于理论知识还是没有一个深刻的概念,索性就动手用Java Socket API 模拟做一个HTTP服务器,巩固一下应用层的知识。</h3>
<blockquote>
HTTP基于TCP协议,协议采用了请求/响应模型。客户端向服务器发送一个请求,请求头包含请求的方法、URL、协议版本、以及包含请求修饰符、客户信息和内容的类似于MIME的消息结构。服务器以一个状态行作为响应,响应的内容包括消息协议的版本,成功或者错误编码加上包含服务器信息、实体元信息以及可能的实体内容——百度百科。
话不多说,还是直接上图。
</blockquote>
具体字段这里不作解释,不懂的请先自己了解http协议。这里主要是根据请求响应这一过程模拟HTTP服务器。
下面是代码:
<pre>
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();
}
}
</pre>
代码看注释也很容易理解。现在我们在浏览器中输入服务器地址+要访问的文件
在看我们控制台输出的内容:
<h5>以上就是Java Socket 简单的模拟HTTP服务器全过程。</h5>