簡體   English   中英

如何在Java的簡單HTTP Web服務器中從客戶端讀取輸入?

[英]How can read input from a Client in a simple HTTP Web Server in Java?

我正在嘗試用Java創建一個簡單的HTTP Web服務器。 我只是一步一步走,所以它非常簡單。 我試圖做到這一點,以便當它們都連接時,我可以從客戶端讀取簡單的輸入,並從服務器輸出任何內容。

在網站上的教程中搜索之后,這是我到目前為止所做的:

public class Server
{
    public static void main(String[] args) throws Exception
    {
        boolean listening = true;
        ServerSocket server = null;
        int port = 2222;
        try
        {
            System.out.println("Server binding to port " + port);
            server = new ServerSocket(port);
        }
        catch(Exception e)
        {
            System.out.println("Error: " + e);
            System.exit(1);
        }

        System.out.println("Server successfully binded to port " + port);

        while(listening)
        {
            System.out.println("Attempting to connect to client");
            Socket client = server.accept();
            System.out.println("Successfully connected to client");
            new ServerThread(client).start() ;
        }

        server.close();
    }
}

public class ServerThread extends Thread
{
    private Socket socket = null ;
    public ServerThread(Socket s)
    {
        this.socket = s ;
    }

    public void run()
    {       
        InputStream in = socket.getInputStream() ;
        OutputStream out = socket.getOutputStream() ;
        byte [] message, reply;
        while((in.read(message))
        {
            out.write(reply) ;
        }
        in.close() ;
        out.close() ;
        socket.close() ;    
    }
}

嘗試連接到客戶端后,它將綁定並掛起。 這是因為我不確定您在ServerThread的while循環中做什么以及如何處理消息和答復變量> _ <自從我完成Java已有很長時間了,所以請放心!

我僅將這種服務器用作“好奇心”,僅需學習一次新的知識,因為您是在重新發明方向盤,安全原因等……我只需要使用一次,因為我必須使用JSON與服務器通信代碼,無法安裝任何服務器。 這段代碼需要做更多的工作,例如我們為每個請求創建一個新線程,更好的RCF HTTP實現,但它可以與您的普通瀏覽器一起使用。

我希望這有幫助。

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class MiniPbxManServer extends Thread {
    private final int PORT = 2222;    
    public static void main(String[] args) {
        MiniPbxManServer gtp = new MiniPbxManServer();
        gtp.start();
    }    
    public void run() {
        try {
            ServerSocket server = new ServerSocket(PORT);
            System.out.println("MiniServer active "+PORT);
            boolean shudown = true;
            while (shudown) {               
                Socket socket = server.accept();                
                InputStream is = socket.getInputStream();
                PrintWriter out = new PrintWriter(socket.getOutputStream());            
                BufferedReader in = new BufferedReader(new InputStreamReader(is));              
                String line;
                line = in.readLine();
                String auxLine = line;
                line = "";
                // looks for post data
                int postDataI = -1;
                while ((line = in.readLine()) != null && (line.length() != 0)) {
                    System.out.println(line);
                    if (line.indexOf("Content-Length:") > -1) {
                        postDataI = new Integer(line
                                .substring(
                                        line.indexOf("Content-Length:") + 16,
                                        line.length())).intValue();
                    }
                }
                String postData = "";
                for (int i = 0; i < postDataI; i++) {
                    int intParser = in.read();
                    postData += (char) intParser;
                }                               
                out.println("HTTP/1.0 200 OK");
                out.println("Content-Type: text/html; charset=utf-8");
                out.println("Server: MINISERVER");
                // this blank line signals the end of the headers
                out.println("");
                // Send the HTML page               
                out.println("<H1>Welcome to the Mini PbxMan server</H1>");
                out.println("<H2>GET->"+auxLine+ "</H2>");        
                out.println("<H2>Post->"+postData+ "</H2>");
                out.println("<form name=\"input\" action=\"imback\" method=\"post\">");
                out.println("Username: <input type=\"text\" name=\"user\"><input type=\"submit\" value=\"Submit\"></form>");                 
                //if your get parameter contains shutdown it will shutdown
                if(auxLine.indexOf("?shutdown")>-1){
                    shudown = false;
                }
                out.close();
                socket.close();
            }
            server.close();            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }    
}

網址:localhost:2222 /無論

我認為您在高層次上正朝着正確的方向前進。 您所擁有的系統與生產系統之間的區別在於,它們對套接字上的輸入進行輪詢是在不同的線程中完成的,以便在等待輸入時不會暫停系統。

實際上,Web服務器的配置參數之一是要啟動並運行多少個客戶端(線程)。

您應該始終從服務器的輸出流中刷新數據。 客戶的響應可能取決於此:

out.flush();

要檢查流的結束,可以使用:

int result = 0;
while ((result = in.read(message)) != -1) {
...

同樣,您的回復消息似乎未初始化,您可能想先重新發送客戶端數據:

reply = message;

jdk包含一個用於構建嵌入式http服務器的簡單HTTP服務器。 看一下這個鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM