📄 threadedserver.java
字号:
import java.io.*;
import java.net.*;
import java.util.Date;
import java.util.StringTokenizer;
public class ThreadedServer {
/*the standard input stream*/
private static BufferedReader stdIn =
new BufferedReader(new InputStreamReader(System.in));
/*the standard output stream*/
private static PrintWriter stdOut =
new PrintWriter(System.out,true);
/*the default socket port*/
private static final int port = 8000;
private ServerSocket serverSocket;
static String hostname = null;
/**the constructor of the ThreadedServer
* */
public ThreadedServer(String h) throws IOException {
serverSocket = new ServerSocket(port);
stdOut.println("Server " + h + "is listening to your request:");
stdOut.flush();
}
/**
* @param creat a socket object and a thread for
* accepting more than one client's request*/
public void service() {
while(true) {
Socket socket = null;
try {
socket = serverSocket.accept();
Thread serverThread = new Thread(new Handler(socket,hostname));
serverThread.start();
} catch(IOException e) {
e.getMessage().toString();
}
}
}
public static void main(String args[]) throws IOException{
stdOut.print("Input the server's name:");
stdOut.flush();
hostname = stdIn.readLine();
new ThreadedServer(hostname).service();
}
}
class Handler implements Runnable {
/*standard input stream*/
private static BufferedReader stdIn =
new BufferedReader(new InputStreamReader(System.in));
/*standard output stream*/
private static PrintWriter stdOut =
new PrintWriter(System.out,true);
/*the default port number*/
static final int DEFAULT_PORT = 8000;
/*the port number request by the client*/
private int port = 0;
/*a identifier shows the request from the client is legal*/
static final int SUCCESS = 200;
/*a identifier shows the request from the client is illegal*/
static final int FAILED = 400;
/*a variable shows the request is legal or not*/
static String responseState = 200 + " OK";
/*a client socket*/
Socket client;
/*the server's name*/
static String hostname = null;
/*the response time */
static Date responseTime;
/*the code name of the erro when the client send a bad request*/
static String ERRO = "";
public Handler(Socket socket,String h) {
hostname = h;
client = socket;
}
public void response(String fileType,long fileLength,FileReader file) throws Exception {
DataOutputStream outToClient =
new DataOutputStream(client.getOutputStream());
String sendToClient = null;
String content = null;
if(fileType == "text/html" || fileType == "txt") {
int i = 0;
while(i<fileLength) {
content += (char)file.read();
i++;
}
}
sendToClient = "HTTP/1.0 " + responseState + "\n"
+"Server: " + hostname + "\n"
+"Date: " + responseTime + "\n"
+"Content-Type: " + fileType + "\n"
+"Content-Length: " + fileLength + "\n"
+"Expires: " + new Date() + "\n"//the time the response end
+ERRO+"Via: " + hostname + " "+DEFAULT_PORT+"\n"
+"Connection: close\n\n";
sendToClient += content;
outToClient.writeBytes(sendToClient);
}
/**
* @param send the information which is requested by the client*/
public void sendMessage() {
String fileType = null;
String newUrl = null;
long fileLength = 0;
boolean containFile = false;
FileReader file = null;
try {
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(client.getInputStream()));
//the request from the client
String command = inFromClient.readLine();
StringTokenizer request= new StringTokenizer(command);
command = request.nextToken();
responseState = FAILED + " Bad Request";
responseTime = new Date();
ERRO = "X_" + hostname +"ERR_INVALID_REQ 0\n";
if(command.equals("GET")) {
String url = "";
//the path of the file which the client request
if(request.countTokens() != 2) {
url = "";
} else {
url = request.nextToken();
}
if(url.startsWith("/")) {
request = new StringTokenizer(url,"/");
newUrl = request.nextToken();
while(request.hasMoreTokens()) {
newUrl = newUrl + "\\" + request.nextToken();
}
if(newUrl.endsWith(".html")) {
fileType = "text/html";
responseTime = new Date();
containFile = true;
} else if(newUrl.endsWith(".jpg")) {
fileType = "image/jpeg";
responseTime = new Date();
containFile = true;
} else if(newUrl.endsWith(".gif")) {
fileType = "image/gif";
responseTime = new Date();
containFile = true;
} else if(newUrl.endsWith(".txt")) {
fileType = "txt";
responseTime = new Date();
containFile = true;
}
}
try {
File f = new File(newUrl);
fileLength = f.length();
//stdOut.println(fileLength);
//stdOut.println(newUrl);
file = new FileReader(newUrl);
stdOut.flush();
if(containFile == true) {
responseState = SUCCESS + " OK";
responseTime = new Date();
ERRO = "";
}
} catch(Exception e) {
e.toString();
//stdOut.println("The file is not existent!");
stdOut.flush();
}
}
this.response(fileType,fileLength,file);
client.close();
} catch (Exception e) {
e.toString();
}
}
public void run(){
this.sendMessage();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -