我下面的代码是一个非常基本的服务器。在浏览器中我输入了类似:localhost:6789 / xxxx的内容。当应用程序运行时,它确实从客户端读取请求,但随后显示消息“无法访问此站点”,并且应用程序抛出异常。回应客户的最佳方式是什么?
import java.net.*;
import java.io.*;
import java.net.Socket;
public class URLConnection {
public static void main(String[] args)throws IOException {
String clientSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
while (true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
outToClient.writeBytes("HTTP/1.1 200 OK");
}
}
}
答案 0 :(得分:1)
您必须关闭OutputStream:
while (true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
outToClient.writeBytes("HTTP/1.1 200 OK");
outToClient.close();
}
答案 1 :(得分:0)
请注意
实际上会有几个clientSentence
(即考虑添加如下的循环)
while (true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
while(true) {
clientSentence = inFromClient.readLine();
if (clientSentence != null && clientSentence.trim().isEmpty()) {
break;
} else {
System.out.println("Received: " + clientSentence);
}
}
outToClient.writeBytes("HTTP/1.1 200 OK\n\nHello world");
outToClient.close();