java - 如何在服务器上接收来自同一客户端的多个 POST 请求
问题描述
我正在尝试编写一个 java 服务器和客户端,以便客户端向服务器发送一个 POST 请求,其中包含从文件中读取的一些 xml 字符串作为有效负载,服务器从客户端获取请求并向其发送确认,并且此过程重复直到客户端已发送的所有 xml 字符串(作为单独的 POST 请求)。
我已经为客户端和服务器之间的 1 次请求和响应的单次交换编写了代码。但是我无法为来自同一个客户端的多个请求扩展它,因为客户端等待服务器的响应并且服务器的响应不会发送到客户端,直到我在 DataOutputStream 对象中写入wr.close()
或写入字节之后。socket.close()
但是,一旦我编写了这两个命令中的任何一个,服务器和客户端之间的连接就会关闭,客户端需要重新建立连接才能发送第二个请求。
这是我的服务器端函数,它接收请求并发送响应:
public HTTPServer(int port) {
try {
private ServerSocket server = new ServerSocket(port);
private Socket socket = server.accept();
int ind = 0;
while (ind<19) {
//socket is an instance of Socket
InputStream is = socket.getInputStream();
InputStreamReader isReader = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isReader);
//code to read and print headers
String headerLine = null;
while ((headerLine = br.readLine()).length() != 0) {
System.out.println(headerLine);
}
ind++;
//send response to the client
Date today = new Date();
String httpResponse = "HTTP/1.1 200 OK\r\n\r\n" + today;
DataOutputStream wr = new DataOutputStream(socket.getOutputStream());
wr.writeBytes(httpResponse);
wr.flush();
}
socket.close(); // or wr.close()
} catch (IOException i) {
System.out.println(i);
}
}
这是我的客户端代码:
public void postMessage() throws IOException {
// string to read message from input
File folder = new File("path/to/my/files");
String[] listOfFiles = folder.list();
for (int i = 0; i < listOfFiles.length; i++) {
File file = new File(listOfFiles[i]);
Scanner sc = null;
try {
sc = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
final URL url = new URL("http://localhost:8080");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
conn.setDoOutput(true);
conn.setConnectTimeout(5000);
// Send post request
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
String line = "";
while (sc.hasNextLine()) {
line += sc.nextLine();
line += '\n';
}
wr.writeBytes(line);
wr.flush();
wr.close();
// read response
BufferedReader in;
if (200 <= conn.getResponseCode() && conn.getResponseCode() <= 299) {
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
}
}
除非我写socket.close()
或wr.close()
之后wr.flush()
,否则我的响应不会发送到客户端并且客户端会一直等待它,但是一旦我这样做,服务器套接字就会关闭并且代码终止。如何在不必关闭套接字的情况下向我的客户端发送响应?
编辑:这是更新的 HTTP 客户端代码,它使用套接字发送 HTTP 请求,但错误仍然存在。
public static void main(String[] args) throws Exception {
InetAddress addr = InetAddress.getByName("localhost");
Socket socket = new Socket(addr, 8080);
boolean autoflush = true;
// string to read message from input
File folder = new File("/Users/prachisingh/IdeaProjects/requests_responses");
String[] listOfFiles = folder.list();
for (int i = 0; i < listOfFiles.length; i++) {
System.out.println("File " + listOfFiles[i]);
File file = new File("/Users/prachisingh/IdeaProjects/requests_responses/" + listOfFiles[i]);
Scanner sc = null;
try {
sc = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String line = "";
while (sc.hasNextLine()) {
line += sc.nextLine();
line += '\n';
}
PrintWriter out = new PrintWriter(socket.getOutputStream(), autoflush);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// send an HTTP request to the web server
out.println("POST / HTTP/1.1");
out.println("Host: http://localhost:8080");
out.println(line);
out.println();
// read the response
boolean loop = true;
StringBuilder sb = new StringBuilder(8096);
while (loop) {
if (in.ready()) {
int r = 0;
while (r != -1) {
r = in.read();
sb.append((char) r);
}
loop = false;
}
}
System.out.println(sb.toString());
}
socket.close();
}
解决方案
推荐阅读
- c - 当我尝试从文本文件加载文本时,我得到了奇怪的被子?
- .htaccess - 在我的网站上获得 SSL 认证的困难
- mutation-observers - 突变观察者可以用来观察单个节点的添加和删除吗?
- python - python csv删除行错误ValueError:list.remove(x):x不在列表中
- python - 使用python中两个列表的值的所有可能组合寻求广义方法来求解方程
- sql - 从数据行进行 SQL 查询
- reactjs - 如何在 Next.js 中使用 getStaticPaths 生成 index.html?
- javascript - Raspberry Node-js GPIO 控制
- javascript - Directus JS SDK 在 API 链接中添加了一个额外的斜线
- ios - 动态更改 CollectionView 的高度以适应内容大小时的错误结果