I am now making TCP socket server using Spring boot integration ip.
public AbstractServerConnectionFactory serverConnectionFactory() {
TcpNioServerConnectionFactory serverConnectionFactory = new TcpNioServerConnectionFactory(port);
serverConnectionFactory.setUsingDirectBuffers(true);
serverConnectionFactory.setSoTcpNoDelay(true);
serverConnectionFactory.setSoKeepAlive(true);
serverConnectionFactory.setSoTimeout(5);
serverConnectionFactory.setSingleUse(false);
// I use ByteArrayStxEtxSerializer provided by Spring boot.
serverConnectionFactory.setSerializer(SERIALIZER);
serverConnectionFactory.setDeserializer(SERIALIZER);
return serverConnectionFactory;
}
My test client code is like this:
Socket sock = new Socket("127.0.0.1", 8081);
OutputStream os = new BufferedOutputStream(sock.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(0x02); // STX
baos.write(0x41); // A
baos.write(0x03); // ETX
System.out.println(Arrays.toString(baos.toByteArray()));
os.write(baos.toByteArray());
os.flush();
String line = null;
while ((line = br.readLine()) != null) {
System.out.println("from server: " + line);
}
os.close();
br.close();
sock.close();
In order to flush output stream into client, I need to set setSingleUse(true)
or setSoTimeout(n)
. Otherwise, it blocks for a while.
I read the following from the official document:
An outbound TCP gateway is provided. It allows for simple request-response processing. If the associated connection factory is configured for single-use connections, a new connection is immediately created for each new request. Otherwise, if the connection is in use, the calling thread blocks on the connection until either a response is received or a timeout or I/O error occurs.
I think my test client waits until timeout for about 2 minutes if I don't set single-use
or timeout
.
How can I force the server to flush output stream into socket instead of single-use
or timeout
?
Thank you.