Java套接字客户端未接收数据
在Java中使用套接字时,我似乎遇到了一些问题。问题在于,客户机没有接收到数据,当它有时确实接收到数据时,数据会延迟很长时间。服务器正确地接收来自客户端的所有数据,并以我希望的方式响应(至少从它的输出中响应)。这方面的任何帮助都会有帮助 服务器:Java套接字客户端未接收数据,java,sockets,Java,Sockets,在Java中使用套接字时,我似乎遇到了一些问题。问题在于,客户机没有接收到数据,当它有时确实接收到数据时,数据会延迟很长时间。服务器正确地接收来自客户端的所有数据,并以我希望的方式响应(至少从它的输出中响应)。这方面的任何帮助都会有帮助 服务器: try{ ServerSocket server = new ServerSocket(6969); while (true){ System.out.println("Listening on
try{
ServerSocket server = new ServerSocket(6969);
while (true){
System.out.println("Listening on port 6969");
Socket client = server.accept();
System.out.println("Accepted");
BufferedReader input = new BufferedReader(new InputStreamReader(client.getInputStream()));
System.out.println("Got the input reader");
//This is where the input data will be stored
StringBuffer sb = new StringBuffer();
while (input.ready()){
System.out.println("Reading data");
int cha = input.read();
if ((cha < 0)){
break;
}
sb.append((char)cha);
}
System.out.println("Recived Data:" + sb.toString());
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
System.out.println(sb.toString().equalsIgnoreCase("INIT"));
if (sb.toString().equalsIgnoreCase("INIT")){
JSONObject jo = new JSONObject();
jo.put("password", "Password123");
jo.put("testString", "tESTsTRING");
jo.put("intTest", 222);
System.out.println("Sending data:" + jo.toString());
output.write(jo.toString());
output.flush();
}
}
}catch (Exception e){
System.out.println(e.getMessage());
}
客户端输出:
Set up connection. Sending data and waiting for response
Got the input reader: 0
此外,服务器有时不会从客户机接收数据,即使它识别出客户机正在尝试发送数据。如果您没有“很好地”关闭套接字,另一方将不会注意到并一直等待数据。
这就是为什么您必须真正考虑在这里处理异常时要做什么,何时阻塞以及阻塞多长时间。只有在下一次尝试读取或写入时抛出IOException,才能发现丢失的连接。“下一步”是指在连接断开后开始的尝试
这个答案几乎没有涵盖所有内容,但我希望这能给你一些提示。如果你使用的是
BufferedReader
,为什么你要逐字阅读而不是逐行阅读?我最初逐行阅读时遇到问题(while循环永远不会中断),这可能是网络问题,您是否在任何重防火墙后面?不,我没有在任何防火墙后面,我正在本地主机上测试它。@Nazgul不,ready()不是阻塞调用。如果他根本不打电话的话,OP的代码会工作得更好。
Listening on port 6969
Accepted
Got the input reader
Reading data
Reading data
Reading data
Reading data
Recived Data:INIT
true
Sending data:{"intTest":222,"testString":"tESTsTRING","password":"Password123"}
Set up connection. Sending data and waiting for response
Got the input reader: 0