spring-boot TCP server: wait for `empty line` before answering a `multi-line` request

You need to set the Deserializer so that Spring knows when to release the read content (so far) to the handler as described in the docs.

In your case, you should write a custom deserializer implementing the interface org.springframework.core.serializer.Deserializer that releases the content to the handler as soon as it has detected two newlines in a row. Make it return a List<String> with the lines sent by Postfix:

class DoubleNewLineDeserializer: Deserializer<List<String>> {

    companion object {
        const val UNIX_NEWLINE = "\n\n"
        const val WINDOWS_NEWLINE = "\r\n\r\n"
        val CRLFRegex = Regex("[\r\n]+")

    override fun deserialize(inputStream: InputStream): List<String> {
        val builder = StringBuilder()
        while(!builder.endsWith(UNIX_NEWLINE) && !builder.endsWith(WINDOWS_NEWLINE))
        return builder.toString().split(CRLFRegex).filter { it.isNotEmpty() }


This deserializer reads input until it finds a double new line (here either \n\n or \r\n\r\n, you can modify this as you want) at which point it removes the message delimiter and then returns the message as a list of lines.

Finally, set your new deserializer on the ServerConnectionFactory:

serverConnectionFactory.deserializer = DoubleNewLineDeserializer()

Input to TCP socket:

[empty line]
[empty line]

Input to handler:

[foo=bar, me=you, year=123]

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top