更新:感谢@MartinFrank 的想法,我将 http header 添加到结果中,并且它有效。
<小时/>HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: result.length()
我正在开发一个客户端程序来使用网络应用程序。 Web 服务器应用程序将向客户端发送“获取”请求。然后客户端程序将开始监听与秤设备连接的 COM 端口,并将结果重量以字符串形式返回到 Web 服务器应用程序。
我尝试使用 ARC 客户端发送请求来测试程序
系统能够打印
Listening for connection on port 8083 ....
Just connected to /0:0:0:0:0:0:0:1:50346
GET /test HTTP/1.1
HOST: localhost:8083
result ??? 3 741g
但请求一直卡在请求阶段,没有响应结果,如下图:
知道如何从客户端程序获得正确的响应吗?感谢您的帮助。
static public void main(String[] args)
{
ServerSocket server;
try {
server = new ServerSocket(8083);
System.out.println("Listening for connection on port 8083 ....");
while (true) {
Socket clientSocket = server.accept();
System.out.println("Just connected to " + clientSocket.getRemoteSocketAddress());
InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream());
BufferedReader reader = new BufferedReader(isr);
String line = reader.readLine();
while (!line.isEmpty()) {
System.out.println(line);
line = reader.readLine();
}
String result = openConnection();.//listen to COM port and return weight result.
var pw = new PrintWriter(clientSocket.getOutputStream(), true);
System.out.print(" result ??? "+result);
pw.println(result);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static String openConnection()
{
if(comPort == null || !comPort.isOpen()) {
comPort = SerialPort.getCommPorts()[0];
comPort.setComPortParameters(2400,7,SerialPort.ONE_STOP_BIT,SerialPort.EVEN_PARITY);
comPort.openPort();
System.out.println("COM port open: " + comPort.getDescriptivePortName());
}else {
System.out.println("COM port already open: " + comPort.getDescriptivePortName());
}
while(fullWeight == null) {
fullWeight = getWeight();
}
return fullWeight;
}
还尝试对结果进行硬编码并删除端口功能。
static public void main(String[] args)
{
....
//String result = openConnection();
String result = "OK";
var pw = new PrintWriter(clientSocket.getOutputStream(), true);
pw.println(result);
}
} catch (IOException e) {
e.printStackTrace();
}
}
最佳答案
我认为您需要刷新 PrintWriter 才能有效发送响应
pw.println(result);
pw.flush();
关于java - 客户端程序响应http请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59657069/