【问题标题】:multithreaded java web server多线程 Java Web 服务器
【发布时间】:2013-03-06 13:20:01
【问题描述】:

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

【问题讨论】:

  • 我认为你必须以 HTTP 格式返回响应
  • 这是怎么做的?我可以阅读任何想法或链接吗?

标签: java multithreading webserver


【解决方案1】:

您永远不会编写 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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      希望对你有帮助

       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();
            }
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-11-02
        • 1970-01-01
        • 2019-05-27
        • 2015-02-10
        • 1970-01-01
        • 2013-11-15
        • 1970-01-01
        相关资源
        最近更新 更多