##示例1 这段代码修改自A Simple Http Server with Java/Socket?。如何处理HTTP很重要。
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class MyHTTPServer {
final static String CRLF = "\r\n";
public static void main(String[] args) throws Exception {
int port = 8000;
ServerSocket serverSocket = new ServerSocket(port);
System.err.println("启动服务,绑定端口: " + port);
while (true) {
Socket clientSocket = serverSocket.accept();
System.err.println("有客户端连接进来了");
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream())
);
PrintWriter out = new PrintWriter(
new BufferedWriter( new OutputStreamWriter(clientSocket.getOutputStream())),
true
);
String data = "";
String s;
while ((s = in.readLine()) != null) {
s += CRLF; // 很重要,默认情况下\r\n被去掉了
data = data + s;
if (s.equals(CRLF)){
break;
}
}
System.out.println(data);
System.err.println("响应");
out.write("HTTP/1.0 200 OK\r\n");
out.write("Server: Apache/0.8.4\r\n");
out.write("Content-Type: text/html\r\n");
out.write("\r\n");
out.write("<TITLE>Exemple</TITLE>");
out.write("<h1>Hello World</h1>");
out.flush();
System.err.println("结束");
out.close();
in.close();
clientSocket.close();
}
}
}
浏览器访问http://127.0.0.1:8000/
即可。
##示例2 代码来自http://www.java2s.com/Code/Java/Tiny-Application/HttpServer.htm。
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;
public class httpServer {
public static void main(String args[]) {
int port = 8001;
ServerSocket server_socket;
try {
server_socket = new ServerSocket(port);
System.out.println("httpServer running on port "
+ server_socket.getLocalPort());
// server infinite loop
while (true) {
Socket socket = server_socket.accept();
System.out.println("New connection accepted "
+ socket.getInetAddress() + ":" + socket.getPort());
// Construct handler to process the HTTP request message.
try {
httpRequestHandler request = new httpRequestHandler(socket);
// Create a new thread to process the request.
Thread thread = new Thread(request);
// Start the thread.
thread.start();
} catch (Exception e) {
System.out.println(e);
}
}
} catch (IOException e) {
System.out.println(e);
}
}
}
class httpRequestHandler implements Runnable {
final static String CRLF = "\r\n";
Socket socket;
InputStream input;
OutputStream output;
BufferedReader br;
public httpRequestHandler(Socket socket) throws Exception {
this.socket = socket;
this.input = socket.getInputStream();
this.output = socket.getOutputStream();
this.br = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
}
public void run() {
try {
processRequest();
} catch (Exception e) {
System.out.println(e);
}
}
private void processRequest() throws Exception {
while (true) {
String headerLine = br.readLine();
System.out.println(headerLine);
if (headerLine.equals(CRLF) || headerLine.equals("")) {
if (headerLine.equals(CRLF)) {
System.out.println("headerLine.equals(CRLF)");
} else {
System.out.println("headerLine.equals(\"\")");
}
break;
}
StringTokenizer s = new StringTokenizer(headerLine);
String temp = s.nextToken();
if (temp.equals("GET")) {
String fileName = s.nextToken();
fileName = "." + fileName;
FileInputStream fis = null;
boolean fileExists = true;
try {
fis = new FileInputStream(fileName);
} catch (FileNotFoundException e) {
fileExists = false;
}
String serverLine = "Server: Simple Java Http Server";
String statusLine = null;
String contentTypeLine = null;
String entityBody = null;
String contentLengthLine = "error";
if (fileExists) {
statusLine = "HTTP/1.0 200 OK" + CRLF;
contentTypeLine = "Content-type: " + contentType(fileName)
+ CRLF;
contentLengthLine = "Content-Length: "
+ (new Integer(fis.available())).toString() + CRLF;
} else {
statusLine = "HTTP/1.0 404 Not Found" + CRLF;
contentTypeLine = "text/html";
entityBody = CRLF+CRLF+"<HTML>"
+ "<HEAD><TITLE>404 Not Found</TITLE></HEAD>"
+ "<BODY>404 Not Found"
+ "<br>usage:http://yourHostName:port/"
+ "fileName.html</BODY></HTML>";
}
// Send the status line.
output.write(statusLine.getBytes());
System.out.println(statusLine);
// Send the server line.
output.write(serverLine.getBytes());
System.out.println(serverLine);
// Send the content type line.
output.write(contentTypeLine.getBytes());
System.out.println(contentTypeLine);
// Send the Content-Length
output.write(contentLengthLine.getBytes());
System.out.println(contentLengthLine);
// Send a blank line to indicate the end of the header lines.
output.write(CRLF.getBytes());
System.out.println(CRLF);
// Send the entity body.
if (fileExists) {
sendBytes(fis, output);
fis.close();
} else {
output.write(entityBody.getBytes());
}
}
}
try {
output.close();
br.close();
socket.close();
} catch (Exception e) {
}
}
private static void sendBytes(FileInputStream fis, OutputStream os)
throws Exception {
byte[] buffer = new byte[1024];
int bytes = 0;
while ((bytes = fis.read(buffer)) != -1) {
os.write(buffer, 0, bytes);
}
}
private static String contentType(String fileName) {
if (fileName.endsWith(".htm") || fileName.endsWith(".html")
|| fileName.endsWith(".txt")) {
return "text/html";
} else if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
return "image/jpeg";
} else if (fileName.endsWith(".gif")) {
return "image/gif";
} else {
return "application/octet-stream";
}
}
}
##示例3 使用线程池
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class httpServer2 {
public static void main(String args[]) {
System.out.println("基于线程池");
int port = 8001;
ServerSocket server_socket;
try {
server_socket = new ServerSocket(port);
System.out.println("httpServer running on port "
+ server_socket.getLocalPort());
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(30);
// server infinite loop
while (true) {
Socket socket = server_socket.accept();
System.out.println("New connection accepted "
+ socket.getInetAddress() + ":" + socket.getPort());
// Construct handler to process the HTTP request message.
try {
httpRequestHandler request = new httpRequestHandler(socket);
// Create a new thread to process the request.
fixedThreadPool.execute(request);
} catch (Exception e) {
System.out.println(e);
}
}
} catch (IOException e) {
System.out.println(e);
}
}
}