gpt4 book ai didi

java - 无法从 Java 服务器应用程序获得响应

转载 作者:可可西里 更新时间:2023-11-01 17:27:24 25 4
gpt4 key购买 nike

下面是一个非常基本的服务器代码。在浏览器中,我输入了类似: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");
}
}

}

最佳答案

你必须关闭输出流:

    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();
}

关于java - 无法从 Java 服务器应用程序获得响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44484931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com