gpt4 book ai didi

java - 向 java 服务器发出 HTTP OPTIONS 请求

转载 作者:行者123 更新时间:2023-12-01 18:11:28 24 4
gpt4 key购买 nike

我有一个java中的服务器类和客户端类。

事实上,我正在本地主机上进行测试,我希望我的服务器能够回答 HTTP 的请求选项。

我不知道我做错了什么,我的客户端服务器收到请求但没有返回我想要的内容,我不明白我做错了什么。

我将客户端类和服务器都留在这里,看看是否有人能解决这个问题。

客户端 TCP

public class clientetcp {

public static void main(String argv[]) throws IOException {

/*
* Leemos los argumentos del programa para saber a qué
* servidor hay que conectarse.
*/
if (argv.length == 0) {
System.err.println("java clientetcp servidor");
System.exit(1);
}


Socket socket = null;
InetAddress address;
byte[] mensaje_bytes = new byte[256];
String mensaje = "";

try {
/*
* Establecemos una conexión con el servidor en el puerto 6001 y
* enviamos lo que el usuario escribe por teclado. Acabamos con la
* palabra end.
*/

address = InetAddress.getByName(argv[0]);
socket = new Socket(address, 6001);
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());

do {

out.writeUTF("GET /index.html HTTP/1.0");
out.writeUTF(""); // blank line separating header & body
out.flush();

String line;
line = in.readUTF();
System.out.println(line);
} while (!mensaje.startsWith("end"));

} catch (Exception e) {
System.err.println(e.getMessage());
System.exit(1);
} finally {

if (socket != null) {
System.out.println("Cerrando socket cliente ...");
socket.close();
}
}

}
}

服务器 TCP

public class servidortcp {

public static void main(String argv[]) throws IOException {
ServerSocket socket = null;
String mensaje;
PrintWriter salida = null;
String salidaOstias;
String pedro;

try {

/*
* Creamos un socket de tipo servidor que escucha en el puerto
* TCP 6001 y espera conexiones de los clientes.
* Este programa recibe lo que viene del socket y lo muestra
* por pantalla.
*/
socket = new ServerSocket(6001);
Socket socket_cli = socket.accept();
DataInputStream in = new DataInputStream(socket_cli.getInputStream());
DataOutputStream out = new DataOutputStream(socket_cli.getOutputStream());
do {
mensaje = in.readUTF();
System.out.println(mensaje);
out.writeUTF("CONTESTO A LO QUE ME HAS DICHO");

} while (1 > 0);
} catch (Exception e) {
if (socket != null) {
System.out.println("Cerrando socket servidor ...");
socket.close();
}
System.err.println(e.getMessage());
System.exit(1);
}
}
}

最佳答案

我没有调试你的代码,但我认为问题出在下面。

在服务器端,您应该为每个接受的连接启动并启动一个单独的线程。但你并没有这样做。

并且您的服务器在主线程中处理所有请求。

在这种情况下,在处理循环的一次迭代(请求)之前,它不会进入另一次迭代,因此不会处理另一个请求。

关于java - 向 java 服务器发出 HTTP OPTIONS 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60463247/

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