我正在尝试实现一个多线程的 Java 网络服务器。
这是我的主要内容:
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 的请求,并且将在这个问题解决后继续构建。