当我输入 localhost:9080/?say=hello 时,我尝试输出 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);
}
}
最佳答案
当然这是一项学校作业,所以我不会给你现成的工作解决方案,只是一些提示。
简化了很多,HTTP 协议(protocol)在客户端和服务器之间交换文本字符串。您的代码已经打印了浏览器发送到您的服务器的字符串;看一下第一行:它说
GET /?say=hello HTTP/1.1
“GET”是一个“HTTP method ”,它后面是您请求的服务器端资源的路径(在本例中只是一个斜杠)加上任何请求参数(问号后面的部分)和协议(protocol)版本。
要对客户端请求的特定路径/参数执行特定操作,您的代码应该检查浏览器提交的第一行文本(例如,您应该检查是否存在 /?say=hello
)。
此外,通常 HTTP 服务器在第一个请求后不会关闭,因此您的代码应该包含另一个无限循环,以在处理第一个连接后等待另一个连接。在将响应发送到浏览器后,您的代码还应该 close()
客户端套接字。
关于java - 如何更改此代码,以便当您输入 localhost :9080/? say=hello 时,它输出 hello?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55351315/