【发布时间】:2014-08-26 07:41:41
【问题描述】:
我似乎在使用 Java 中的套接字时遇到了一些问题。问题是客户端不接收数据,而且有时它确实接收到数据时,数据会延迟很长时间。服务器正确接收来自客户端的所有数据并响应我想要的方式(至少从它的输出中)。对此的任何帮助都会有所帮助。
服务器:
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());
}
客户:
try{
Socket connection = new Socket(host, 6969);
System.out.println("Set up connection. Sending data and waiting for response");
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
output.write("INIT");
output.flush();
BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
System.out.println("Got the input reader: " + connection.getInputStream().available());
//This is where the input data will be stored
StringBuffer sb = new StringBuffer();
System.out.println(input.readLine() + " :: " + input.ready());
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());
}catch (Exception e){
e.printStackTrace();
}
服务器控制台输出:
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
此外,服务器有时不会从客户端接收数据,即使它识别出客户端正在尝试发送数据。
【问题讨论】:
-
如果您使用的是
BufferedReader,为什么要逐个字符而不是逐行读取? -
我最初在逐行阅读时遇到问题(while 循环永远不会中断)
-
看来可能是网络问题,您是否有过重的防火墙?
-
不,我没有安装任何防火墙,我正在本地主机上进行测试。
-
@Nazgul 不,ready() 不是阻塞调用。如果他根本不调用 OP 的代码会更好地工作。