java - 如何在 Java 中的简单 HTTP Web 服务器中读取客户端的输入?

标签 java http webserver

我正在尝试用 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() ;    
    }
}

它会绑定(bind),然后在尝试连接到客户端后挂起。这是因为我不确定你在 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();
        }
    }    
}

网址:本地主机:2222/随便

关于java - 如何在 Java 中的简单 HTTP Web 服务器中读取客户端的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12770052/

相关文章:

c# - ASP.Net MVC 4 PUT 请求响应 409 - 冲突

web-services - 将 Nginx 上的请求从 GET 重写为带有正文的 POST(用于跟踪像素)

php - Apache suExec 在 Plesk 11 中不工作 [仍在使用 www-data 默认用户]

java - 从现有的创建自定义 Swing 组件

java - Simple XML 库实际上如何创建和填充对象?

python-requests - 通过带有方括号名称的 POST 表单发送不起作用

java - Android从restful服务读取json

nginx - 如何为 nginx 中的所有服务器设置默认指令? (Plesk 的问题)

Java字符串转JS

Java Hashset 基于值而不是哈希码存储项目