import java.io.*;
import java.net.*;
import java.util.Spliterator;
public class HttpServer {//主线程
public static void main(String[] args)
{
int port;
//获得端口号
ServerSocket serverSocket;
try
{
port=Integer.parseInt(args[0]);
}
catch(Exception e)
{
port=8888;
}
try
{
serverSocket=new ServerSocket(port);
while(true)
{
final Socket socket=serverSocket.accept();
Service s = new Service(socket);
Thread t = new Thread(s);
t.start();
}
}
catch(Exception e){e.printStackTrace();}
}
}
class Service implements Runnable//分线程
{
private Socket socket;
public Service(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
service(this.socket);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void service(Socket socket)throws Exception
{
/*读取http请求信息*/
InputStream socketIn=socket.getInputStream();
Thread.sleep(500);
int size=socketIn.available();
byte[] buffer=new byte[size];
socketIn.read(buffer);
String request=new String(buffer);
/*解析Http请求数据*/
//获得请求的第一行信息
String firstLineOfRequest=request.substring(0,request.indexOf("\r\n"));
//解析第一行信息
String[] parts=firstLineOfRequest.split(" ");
String uri=parts[1];
/*得到http响应正文的类型*/
String contentType;
if(uri.indexOf("html")!=-1 || uri.indexOf("htm")!=-1)
contentType="text/html";
else if (uri.indexOf("jpg")!=-1 || uri.indexOf("jpeg ")!=-1)
contentType="image/jpeg";
else if (uri.indexOf("gif")!=-1)
contentType="image/gif";
else
contentType="application/octet-stream";
System.out.println(uri);
/*响应*/
String responseFirstLine="HTTP/1.1 200 OK\r\n";
String responseHeader="Content-Type:"+contentType+"\r\n\r\n";
InputStream in=HttpServer.class.getResourceAsStream("root"+uri);
OutputStream socketOut=socket.getOutputStream();
socketOut.write(responseFirstLine.getBytes());
socketOut.write(responseHeader.getBytes());
int len=0;
buffer=new byte[128];
while((len=in.read(buffer))!=-1) socketOut.write(buffer,0,len);
Thread.sleep(1000);
socket.close();
}
}
步骤1:保存为 HttpServer.java
注意:图片中h是小写,代码文件名是大写HttpServer
步骤2:进入保存路径
步骤3:
javac httpServer.java
步骤4:
步骤5:
步骤6:
建议firefox打开,别的浏览器不太好用