該程序簡單實現web服務器
import java
import
import java
public class SimpleWebServer {
public static void main(String argv[]) throws Exception {
//Get the port as an argument
// Also
int port = (new Integer(argv[
// Establish the listen socket
ServerSocket socket = new ServerSocket(port);
while(true){
// Listen for a TCP connection request
Socket connection = socket
processRequest(connection);
}
}
private static void processRequest(Socket connection) throws Exception {
final String CRLF =
Socket socket = connection;
// Get a reference to the socket
InputStream is = socket
DataOutputStream os = new DataOutputStream(socket
// Set up input stream filters
BufferedReader br = new BufferedReader(new InputStreamReader(is));
// Get the request line of the HTTP request message
String requestLine = br
// Extract the filename from the request line
StringTokenizer tokens = new StringTokenizer(requestLine);
tokens
String fileName = tokens
// Prepend a
fileName =
// Open the requested file
FileInputStream fis = null ;
boolean fileExists = true ;
try {
fis = new FileInputStream(fileName);
} catch (FileNotFoundException e) {
fileExists = false ;
}
// Construct the response message
String statusLine = null;
String contentTypeLine = null;
String entityBody = null;
if (fileExists) {
statusLine =
contentTypeLine =
contentType(fileName) + CRLF;
} else {
statusLine =
contentTypeLine =
entityBody =
}
// Send the status line
os
// Send the content type line
os
// Send a blank line to indicate the end of the header lines
os
// Send the entity body
if (fileExists) {
sendBytes(fis
fis
} else {
fileExists = false;
os
}
// Close streams and socket
os
br
socket
}
private static void sendBytes(FileInputStream fis
OutputStream os) throws Exception {
// Construct a
byte[] buffer = new byte[
int bytes =
// Copy requested file into the socket
while ((bytes = fis
os
}
}
private static String contentType(String fileName) {
if(fileName
return
}
else if (fileName
return
}
else if (fileName
return
}
return
}
}
From:http://tw.wingwit.com/Article/program/Java/hx/201311/25715.html