Background:
Server-side communication: TCP/IP socket short link.
First look at my original socket code:
public static byte[] sendMessage(String url, int port, byte[] request, int timeout) {
byte[] res = null;
Socket socket = null;
InputStream is = null;
OutputStream os = null;
try {
socket = new Socket(url, port);
socket.setSoTimeout(timeout);
is = socket.getInputStream();
os = socket.getOutputStream();
os.write(request);
os.flush();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[8192];
int count;
while ((count = is.read(buffer)) != -1) {
bos.write(buffer, 0, count);
}
res = bos.toByteArray();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (os != null) {
os.close();
}
if (is != null) {
is.close();
}
if (socket != null) {
socket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return res;
}
The above code is the most commonly used way to send sockets. It is suitable for general socket links. But there's always been a mistake when it comes to interfacing with banks.
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:196)
at java.net.SocketInputStream.read(SocketInputStream.java:122)
at java.net.SocketInputStream.read(SocketInputStream.java:108)
Questions are described as follows:
1. If one end of the Socket is closed (or actively closed, or closed due to an exception exit), the other end still sends data, and the first packet sent raises the exception (Connect reset by peer).
2. One end exits, but the connection is not closed when it exits, and the other side throws the exception if it reads data from the connection. Simply put, it is caused by read and write operations after disconnection.
I'm a client here, and the socket is finally closed for only 2 reasons. This means that the socket is closed after the other party returns the data, while the client is still reading the data. So connect reset.
Solution;
Use InputStream. available determines whether there are still readable bytes
available()
Returns the estimated number of bytes remaining for the next call to this input stream that can be read (or skipped) from this input stream without blocking.
As follows:
public static byte[] sendMessage(String url, int port, byte[] request) {
byte[] res = null;
Socket socket = null;
InputStream is = null;
OutputStream os = null;
try {
socket = new Socket(url, port);
os = socket.getOutputStream();
os.write(request);
os.flush();
is = socket.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int count = 0;
do {
count = is.read(buffer);
bos.write(buffer, 0, count);
} while (is.available() != 0);
res = bos.toByteArray();
os.close();
is.close();
socket.close();
} catch (Exception ex) {
try {
if (is != null) {
is.close();
}
if (socket != null)
socket.close();
} catch (Exception e) {
}
}
return res;
}