我想實現一個多線程的Java Web服務器。多線程的Java Web服務器
這裏是我的主:
import java.net.*;
public class Main {
public static void main(String argv[]) throws Exception{
ServerSocket welcomeSocket = new ServerSocket(6790);
while(true){
System.out.println("Waiting...");
Socket cSock = welcomeSocket.accept();
System.out.println("Accepted connection : " + cSock);
Server a = new Server(cSock);
a.start();
}
}
}
這裏是我的線程類:
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Server extends Thread{
Socket cSock;
Server(Socket cSock){ //constructor
this.cSock = cSock;
}
public void run(){
try{
String request;
Scanner inFromClient = new Scanner(cSock.getInputStream());
DataOutputStream outToClient = new DataOutputStream(cSock.getOutputStream());
request = inFromClient.nextLine();
System.out.println("Received: "+request);
//trimming URL to extract file name
String reqMeth = request.substring(0, 3);
String reqURL = request.substring(5, (request.lastIndexOf("HTTP/1.1")));
String reqProto = request.substring(request.indexOf("HTTP/1.1"));
System.out.println("Request Method:\t" +reqMeth +"\nRequest URL:\t" +reqURL+ "\nRequest Protocol: " +reqProto);
//passing file name to open
File localFile = new File(reqURL.trim());
byte [] mybytearray = new byte [(int)localFile.length()];
FileInputStream fis = new FileInputStream(localFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
//sending file to stream
System.out.println("Sending...");
outToClient.write(mybytearray,0,mybytearray.length);
outToClient.flush();
outToClient.close();
}catch(Exception e){
System.out.println(e);
}
}
}
通過邏輯,每個請求的服務器上獲取,它會創建一個新的線程。每個線程都與特定的請求相關聯。 我的問題是,當我請求一個文件(例如index.html)時,服務器獲取請求,但文件未加載,瀏覽器繼續加載。
我想出了每個線程都已啓動但未完成。
這裏是輸出:
Waiting...
Accepted connection : Socket[addr=/192.168.0.10,port=58957,localport=6790]
Waiting...
Accepted connection : Socket[addr=/192.168.0.10,port=58958,localport=6790]
Waiting...
Received: GET /html/index.html HTTP/1.1
Request Method: GET
Request URL: html/index.html
Request Protocol: HTTP/1.1
Accepted connection : Socket[addr=/192.168.0.10,port=59093,localport=6790]
Waiting...
Received: GET /index.html HTTP/1.1
Request Method: GET
Request URL: index.html
Request Protocol: HTTP/1.1
我到底做錯了什麼?有沒有更好的辦法?請注意,我只用一個線程來測試來自一個IP的請求,並且將建立起來,而不是一旦解決這個問題。
我認爲你必須以HTTP格式返回響應 – Behnil 2013-03-06 13:25:05
這是如何完成的?我可以閱讀的任何想法或鏈接? – user2114721 2013-03-06 13:26:31