4

我正在尝试实现一个多线程的 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 的请求,并且将在这个问题解决后继续构建。

4

3 回答 3

2

您永远不会编写 HTTP 标头。

outToClient.write("HTTP/1.0 200 OK\r\n");
outToClient.write("Connection: Close\r\n");
outToClient.write("\r\n");
outToClient.write(mybytearray,0,mybytearray.length);

如果您要实现自己的服务器,您应该阅读RFC 2616

于 2013-03-06T13:29:43.063 回答
1

如果要使用浏览器连接到服务器,它必须返回带有标头的 HTTP 响应。 是一个简单的 HTTP 服务器示例。或者更好地查看这个已回答的问题。

于 2013-03-06T13:31:14.480 回答
0

希望这可以帮助

 import java.io.*;
 import java.net.*;
 import java.nio.file.Files;
 import java.awt.image.BufferedImage;

 import javax.imageio.ImageIO;



 public class TCPServer
 {
 public static void main(String[] argv) throws IOException//IOException
 {
    ServerSocket welcomeSocket = new ServerSocket(9080);

    while(true)
    {
        Socket connectionSocket = welcomeSocket.accept();
        BufferedReader inFromClient = new BufferedReader(new       InputStreamReader(connectionSocket.getInputStream()));
        DataOutputStream outToClient = new     DataOutputStream(connectionSocket.getOutputStream());

        Thread thread = new ClientHandler(connectionSocket, inFromClient,     outToClient);
        thread.start();
    }
}

}

 class ClientHandler extends Thread{
   Socket connectionSocket;
   BufferedReader inFromClient;
   DataOutputStream outToClient;

  public ClientHandler(Socket connectionSocket, BufferedReader inFromClient,     DataOutputStream outToClient) {
    this.connectionSocket = connectionSocket;
    this.inFromClient = inFromClient;
    this.outToClient = outToClient;
  }

   public void run()
   {
      String clientSentence;
      try
      {

          System.out.println("A new client is connected : " + connectionSocket);
          clientSentence = inFromClient.readLine();
          System.out.println("Received: " + clientSentence);
          String[] tokens = clientSentence.split("\\s+");

          if(tokens[1].equals("/index.html") || tokens[1].equals("/"))
          {

              File file = new File(System.getProperty("user.dir")+"/index.html");
              Files.copy(file.toPath(), outToClient);
          }else if(tokens[1].equals("/RealIndex.html"))
          {
              File file = new     File(System.getProperty("user.dir")+"/RealIndex.html");
              Files.copy(file.toPath(), outToClient);
          }
          else if(tokens[1].equals("/hqdefault.jpg"))
          {
              File file = new     File(System.getProperty("user.dir")+"/hqdefault.jpg");
              BufferedImage image = ImageIO.read(file);
              outToClient.writeBytes("HTTP/1.1 200 OK\n\n");
              ImageIO.write(image,"JPG", outToClient);
          }
          else
          {
              File file = new     File(System.getProperty("user.dir")+"/404Error.html");
              Files.copy(file.toPath(), outToClient);
          }

          this.connectionSocket.close();
          this.outToClient.close();
          this.inFromClient.close();
      }catch (IOException e)
      {
          e.printStackTrace();
      }
  }
}
于 2019-10-04T15:37:55.117 回答