package network;
import java.io.*;
import java.net.*;
import java.util.*;
public class HTTPServerV2 {
public static void main(String[] args) {
int port;
ServerSocket serverSocket;
// 设置服务器使用的端口
try {
port = Integer.parseInt(args[0]);
} catch (Exception e) {
System.out.println("port = 8080 (默认)");
port = 8080; //默认端口为8080
}
try {
serverSocket = new ServerSocket(port);
System.out.println("服务器正在监听端口:" + serverSocket.getLocalPort());
while (true) { //服务器在一个无限循环中不断接收来自客户的TCP连接请求
try {
//等待客户的TCP连接请求
final Socket socket = serverSocket.accept();
System.out.println("建立了与客户的一个新的TCP连接,该客户的地址为:" + socket.getInetAddress() + ":" + socket.getPort());
service(socket); //响应客户请求
} catch (Exception e) {
System.out.println("客户端请求的资源不存在");
}
} //#while
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 响应客户的HTTP请求
*/
public static void service(Socket socket) throws Exception {
/*读取HTTP请求信息*/
InputStream socketIn = socket.getInputStream(); //获得输入流
Thread.sleep(500); //睡眠500毫秒,等待 HTTP 请求
//在进行网络操作时往往出错,因为你调用 available()方法时,对方发送的数据可能还没有到达,你得到的count是0 。
int size = socketIn.available();
byte[] requestBuffer = new byte[size];
socketIn.read(requestBuffer);
String request = new String(requestBuffer);
System.out.println("---------------------请求内容-----------------------");
System.out.println(request); //打印HTTP请求数据
System.out.println("--------------------------------------------");
/*解析HTTP请求*/
//获得 HTTP 请求的第一行
int endIndex = request.indexOf("\r\n");
if (endIndex == -1)
endIndex = request.length();
String firstLineOfRequest = request.substring(0, endIndex);
//解析 HTTP 请求的第一行
String[] parts = firstLineOfRequest.split(" ");
String uri = "";
if (parts.length >= 2) {
uri = parts[1]; //获得 HTTP 请求中的 uri
System.out.println(uri);
}
/*决定HTTP响应正文的类型*/
String contentType;
if (uri.contains("html") || uri.contains("htm"))
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 if (uri.indexOf("ico") != -1)
contentType = "image/x-icon";
else
contentType = "application/octet-stream";
/*创建HTTP响应结果 */
//HTTP响应的第一行
String responseFirstLine = "HTTP/1.1 200 OK\r\n";
//HTTP响应头
String responseHeader = "Content-Type:" + contentType + "\r\n\r\n";
//获得读取响应正文数据的输入流
FileInputStream in = new FileInputStream("webapps/root/" + uri);
InputStreamReader inputStreamReader = new InputStreamReader(in);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
/*发送HTTP响应结果 */
OutputStream socketOut = socket.getOutputStream(); //获得输出流
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(socketOut);
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
bufferedWriter.write(responseFirstLine);
bufferedWriter.write(responseHeader);
bufferedWriter.flush();
String line = null;
while (null!= (line = bufferedReader.readLine())){
bufferedWriter.write(line);
bufferedWriter.newLine();
bufferedWriter.flush();
}
Thread.sleep(1000); //睡眠1秒,等待客户接收HTTP响应结果
socket.close(); //关闭TCP连接
}
}
默认情况下,需要指定请求的文件内容,而不是默认的资源“/”。例如在浏览器中输入的网址为:http://127.0.0.1:8080/index.htm 或者?http://127.0.0.1:8080/index.html。
还可以将网站的图标存放到资源的文件夹(webapps/root)中,这样就可以在浏览器中显示当前网站的图标了。http://127.0.0.1:8080/index.htm 或者?
|