?? threadedserver.java
字號:
/**
* @author wenhuaxiao
* @see <code>Client.java</code> and
* @version 1.0
*
*/
import java.net.*;
import java.util.StringTokenizer;
import java.io.*;
class Handler implements Runnable{
private Socket socket;
public Handler(Socket s){
Thread t;
socket = s;
t = new Thread(this, "Handler Thread");
t.start();
}
public void run() {
try {
// Read the request from client
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(socket.getInputStream()));
String requestMessageLine;
requestMessageLine = inFromClient.readLine();
// Process the request
StringTokenizer tokenizedLine =
new StringTokenizer(requestMessageLine);
if (tokenizedLine.nextToken().equals("GET")) {
String fileName;
// Parse URL to retrieve file name
fileName = tokenizedLine.nextToken();
if (fileName.startsWith("/") == true )
fileName = "C:\\www\\test\\" + fileName.substring(1);
File file = new File(fileName);
int numOfBytes = (int) file.length();
FileInputStream inFile = new FileInputStream (fileName);
byte[] fileInBytes = new byte[numOfBytes];
inFile.read(fileInBytes);
// Get output stream
DataOutputStream outToClient =
new DataOutputStream(socket.getOutputStream());
// Generate response header
outToClient.writeBytes("HTTP/1.0 200 Document Follows\r\n");
if (fileName.endsWith(".jpg"))
outToClient.writeBytes("Content-Type: image/jpeg\r\n");
if (fileName.endsWith(".gif"))
outToClient.writeBytes("Content-Type: image/gif\r\n");
outToClient.writeBytes("Content-Length: " + numOfBytes + "\r\n");
outToClient.writeBytes("\r\n");
// Send file content
outToClient.write(fileInBytes, 0, numOfBytes);
// Close connection
socket.close();
} else {
System.out.println("Bad Request Message");
}
} catch (Exception e) {
System.out.println("Error");
} // End of catch
} // End of run()
}
class ThreadedServer {
// The connetion port number.
private static final int serverPort = 6789;
public static void main(String args[]) {
// Create server socket
ServerSocket listenSocket = null;
try {
listenSocket = new ServerSocket(serverPort);
} catch (IOException e) {
System.err.println("IO erro when \"ServerSocket(serverPort)\" ");
e.printStackTrace();
}
System.out.println("server listening at " + listenSocket);
while (true) {
// Take a ready connection from the accepted queue
Socket connectionSocket = null;
try {
connectionSocket = listenSocket.accept();
} catch (IOException e) {
System.err.println("IO erro when \"listenSocket.accept()\" ");
e.printStackTrace();
}
System.out.println("receive request from " + connectionSocket);
// Dispatch a request server
new Handler( connectionSocket );
} // End of while (true)
} // End of main
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -