?? server.java
字號:
/**
* @(#)Server.java
*
* @author Xia Chang'an
* @version 1.0
*/
import java.io.*;
import java.net.*;
import java.util.*;
/**
* This is a server creating a socket with port number 8000 and waits for
* incoming requests.
*/
public class Server {
private static String CRLF = "\r\n";
/**
* The main function of the class.
*/
public static void main(String[] args) {
Server server = new Server();
try {
server.processRequest();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* This method is used to processRequest from the client or user.
*/
private void processRequest() throws Exception {
/**
* The server socket banding to port 8000.
*/
ServerSocket listenSocket = new ServerSocket(8000);
/**
* Infinate loop for accepting incoming connections. Handle one request
* at a time.
*/
while (true) {
/*
* Print the prompt message in the terminal.
*/
System.out.println("The server is now waiting for request...");
Socket connectionSocket = listenSocket.accept();
/**
* Receive the request message from the client.
*/
String requestMessage = "";
boolean readFinish = false;
/*
* The buffer reader used to get request message from the client.
*/
DataInputStream inFromClient = new DataInputStream(connectionSocket
.getInputStream());
/*
* the output stream used to export to the client terminal.
*/
DataOutputStream outToClient = new DataOutputStream(
connectionSocket.getOutputStream());
/*
* get the request message.
*/
requestMessage = inFromClient.readLine().toString();
/*
* parse the ruquest message.
*/
StringTokenizer tokenizedline = new StringTokenizer(requestMessage);
String command = tokenizedline.nextToken();
/*
* If it is a GET request.
*/
if (command.equals("GET"))
{
String url = tokenizedline.nextToken();
String httpVersion = tokenizedline.nextToken();
processGet(outToClient, url);
} else if (command.equals("PUT"))
{
int len = 0;
String url = tokenizedline.nextToken();
StringTokenizer tokens = new StringTokenizer(requestMessage,CRLF);
while (tokens.hasMoreTokens())
{
String token = tokens.nextToken();
if (token.startsWith("Content-Length:"))
{
String lengthStr = token
.substring(token.indexOf(' ') + 1);
len = new Integer(lengthStr).intValue();
break;
}
}
if (len > 0)
{
processPut(inFromClient, outToClient, url, len);
} else
{
outToClient.write(buildErrorPage(400, "Bad Request.").getBytes());
}
} else
{
outToClient.write((buildErrorPage(501, "Not Implemented")).getBytes());
}
}
}
private void processPut(DataInputStream inFromClient,
DataOutputStream outToClient, String filename, int len)
{
try {
if (filename.startsWith("/") == true)
filename = filename.substring(1);
File file = new File(filename);
String feedback;
if (file.exists())
{
if (!file.isFile())
{
outToClient.write((buildErrorPage(403, "Forbidden")).getBytes());
return;
} else
{
feedback = buildErrorPage(200, "OK");
}
} else {
feedback = buildErrorPage(201, "Created");
}
/**
* Create a file stream.
*/
FileOutputStream fstream = new FileOutputStream(file);
byte[] buffer = new byte[1000];
int count = 0;
while (count < len && ((count += inFromClient.read(buffer)) != -1))
{
fstream.write(buffer);
}
/**
* Be sure to flush the output stream.
*/
fstream.flush();
outToClient.write(feedback.getBytes());
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
private void processGet(DataOutputStream outToClient, String filename) {
try {
if (filename.startsWith("/") == true)
filename = filename.substring(1);
File file = new File(filename);
/**
* if the file not found
*/
if (!file.isFile())
{
outToClient.write(buildErrorPage(404, "Not Found " + filename)
.getBytes());
} else
{
int numberOfBytes = (int) file.length();
FileInputStream inFile = new FileInputStream(filename);
byte[] fileInBytes = new byte[numberOfBytes];
inFile.read(fileInBytes);
outToClient.writeBytes("HTTP/1.0 200 OK" + CRLF);
if (filename.endsWith(".jpg") || filename.endsWith(".JPG"))
outToClient.writeBytes("Content-type:" + "image/jpeg"
+ CRLF);
if (filename.endsWith(".gif") || filename.endsWith(".GIF"))
outToClient
.writeBytes("Content-type:" + "image/gif" + CRLF);
if (filename.endsWith(".htm") || filename.endsWith(".html"))
outToClient
.writeBytes("Content-type:" + "text/html" + CRLF);
outToClient
.writeBytes("Content-Length:" + numberOfBytes + CRLF);
outToClient.writeBytes(CRLF);
outToClient.write(fileInBytes, 0, numberOfBytes);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private String buildErrorPage(int ErrorNo, String msg)
{
String content = "<html>" + CRLF + "<head>" + CRLF
+ " <title>Java Http 1.0 Server- Error report </title>"
+ CRLF + "</head>" + CRLF + "<body>" + CRLF
+ " <h1>HTTP Status " + ErrorNo + "\n" + msg + "</h1>" + CRLF
+ "</body>" + "</html>" + CRLF;
String header = "HTTP/1.0" + " " + ErrorNo + " " + msg + CRLF;
header += ("Content-type: text/html" + CRLF);
header += ("Content-Length:" + content.length() + CRLF + CRLF);
return (header + content);
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -