如何更改此代码,以便当您输入localhost:9080 /?say = hello时,它输出hello?

时间:2019-03-26 06:51:56

标签: java serversocket

当我输入enter localhost:9080 /?say = hello时,我试图输出问候。但我不知道该怎么做

public class MyServer {
    public static void main(String args[])throws Exception{
        ServerSocket ss=new ServerSocket(9080);
        Socket client = ss.accept();
        Scanner in =new Scanner(client.getInputStream());
        // running infinite loop for getting
        // client request
        while (true){
            String s = in.nextLine();
            if (s==null || s.trim().length()==0)
                break;
            System.out.println(s);
        }
        PrintWriter out = new PrintWriter(client.getOutputStream(),true);
        String document = "<html><body>Salem</body></html>";
        String response = "HTTP/1.1 200 OK\r\n" +
                "Server: YarServer/2009-09-09\r\n" +
                "Content-Type: text/html\r\n" +
                "Content-Length: " + document.length() + "\r\n" +
                "Connection: close\r\n\r\n";
        out.println(response+document);

    }
}

1 个答案:

答案 0 :(得分:1)

当然,这是学校的工作,因此,仅提供一些提示,我不会为您提供现成的工作解决方案。

简化很多,HTTP协议在客户端和服务器之间交换文本字符串。您的代码已经打印出浏览器发送到您服务器的字符串。看看第一行:它说

 GET /?say=hello HTTP/1.1

“ GET”是“ HTTP method”,后跟您请求的服务器端资源的路径(在这种情况下为斜杠)加上任何请求参数(问号后的部分)和协议版本。

要对客户端请求的特定路径/参数执行特定操作,您的代码应检查浏览器提交的第一行文本(例如,应检查/?say=hello的存在)。 / p>

此外,通常在第一个请求后HTTP服务器不会关闭,因此您的代码应包含另一个无限循环,以在为第一个请求服务后等待另一个连接。将响应发送到浏览器后,您的代码还应该close()客户端套接字。