我写的是客户端,对接远程服务端,报文能成功发送,但是报Connection reset。
这个问题卡了我三天,总算解决了!!!
原因:
就是客户端在接受服务端的响应时,没有对循环while ((info = br.readLine()) != null)读出的信息进行判断,导致无法跳出循环直至对端关闭连接,然后客户端抛异常。
必须要判断字符串已经全部取完!!
while ((info = br.readLine()) != null) {
sb.append(info + "\n");
//这里必须要判断返回值,不然不会跳出循环,直到对端关闭连接抛reset异常
if(sb.toString().indexOf("</Service>")!=-1){
break;
}
}
public class Client {
/**
* 客户端发送和接收
*
* @param xmlMsgBO
* @param sn
* @return
* @throws Exception
*/
public void client(String xmlMsgBO, String sn) throws Exception {
Socket socket = new Socket("xxx.xxx.xxx.xxx", 9052);
BufferedWriter bw = null;
BufferedReader br = null;
try {
//发送请求
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write(xmlMsgBO);
bw.flush();
socket.shutdownOutput();
//接收返回信息
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String info = null;
StringBuffer sb = new StringBuffer();
while ((info = br.readLine()) != null) {
sb.append(info + "\n");
//这里必须要判断返回值,不然不会跳出循环,直到对端关闭连接抛reset异常
if(sb.toString().indexOf("</Service>")!=-1){
break;
}
}
String str = sb.substring(sb.indexOf("<"), sb.length());
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(br);
IOUtils.closeQuietly(bw);
IOUtils.closeQuietly(socket);
}
}
}