?? jv.txt
字號:
import java.io.* ;
import java.net.* ;
import java.util.* ;
public final class WebServer
{
public static void main(String args[]) throws Exception
{
int port = 1234;
ServerSocket welcomeSocket = new ServerSocket(port);
while (true) {
HttpRequest request = new HttpRequest(welcomeSocket);
Thread thread = new Thread(request);
thread.start();
}
}
}
final class HttpRequest implements Runnable
{
final static String CRLF = "\r\n";
Socket socket;
public HttpRequest(ServerSocket WelcomeSocket) throws Exception
{
this.socket = WelcomeSocket.accept();
}
public void run()
{
try {
processRequest();
} catch (Exception e) {
System.out.println(e);
}
}
private void processRequest() throws Exception
{
DataOutputStream os = new DataOutputStream(this.socket.getOutputStream());
InputStreamReader isr = new InputStreamReader(this.socket.getInputStream());
BufferedReader br = new BufferedReader(isr);
// Get the request line of the HTTP request message.
String requestLine = br.readLine();
// Display the request line.
System.out.println("Display the client's request message");
System.out.println(requestLine);
String headerLine = null;
while ((headerLine = br.readLine()).length() != 0) {
System.out.println(headerLine);
}
StringTokenizer tokens = new StringTokenizer(requestLine);
tokens.nextToken(); // skip over the method, which should be "GET"
String fileName = tokens.nextToken();
fileName = "." + fileName;
FileInputStream fis = null;
boolean fileExists = true;
try {
fis = new FileInputStream(fileName);
} catch (FileNotFoundException e) {
fileExists = false;
}
String statusLine = null;
String contentTypeLine = null;
String entityBody = null;
if (fileExists) {
statusLine = "statusLine";
contentTypeLine = "Content-type: " +
contentType( fileName ) + CRLF;
} else {
statusLine = "404 Not Found " + CRLF;
contentTypeLine = "contentTypeLine" + CRLF;
entityBody = "<HTML>" + "<HEAD><TITLE>Not Found</TITLE></HEAD>" +"<BODY>Not Found</BODY></HTML>";
}
os.writeBytes(statusLine);
os.writeBytes(contentTypeLine);
os.writeBytes(CRLF);
if (fileExists) {
sendBytes(fis, os);
fis.close();
} else {
os.writeBytes("Error");
}
isr.close();
os.close();
br.close();
socket.close();
}
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")) {
return "text/html";
}
if(fileName.endsWith(".gif") ) {
return "image/gif";
}
if(fileName.endsWith(".jpeg")) {
return "image/jpeg";
}
return "application/octet-stream";
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -