Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What would be the Spring way of using TCP connections?

I am reading and write XML over a TCP connection (not HTTP) as part of a web service I'm developing, and I was wondering whether there is a more "springified" way (or even other ideas) of achieving what I'm trying below:

    InputStream is = null;
    OutputStream os = null;
    Socket s = null;
    try {
        s = new Socket(address, portNo);
        os = s.getOutputStream();
        os.write(msg.getBytes());
        os.flush();
        is = s.getInputStream();
        String xml = IOUtils.toString(is);
        return xml;
    } finally {
        IOUtils.closeQuietly(os);
        IOUtils.closeQuietly(is);
        if (s != null) s.close();
    }

Note, I've got no control over the server, so I don't think I'll be able to use Spring remoting, but was wondering whether this can be improved akin to spring's JdbcTemplates.

EDIT:

Note, just to clarify IOUtils is Apache commons-io...

like image 622
beny23 Avatar asked Jan 19 '10 14:01

beny23


2 Answers

I have a similar problem and think of using Spring Integration for this, sounds like a perfect fit to me:

  • Spring-Integration Home
  • Spring Integration Reference (TCP/UDP Adapters)
  • TCP Connection Javadocs

Note that Spring Integration 2.0 builds on top of Spring 3.0, whereas the previous 1.0 version also supports Spring 2.x (but does not include the TCP/UDP Adapter).

like image 54
Gregor Avatar answered Oct 17 '22 08:10

Gregor


The "Spring approach" applies here not to how you do the TCP socket communications but how the classes that colloborate with this class interact with it.

So I think the "Spring approach" would be to hide any sort of socket communication behind a MessageSender (horrible name, I know) interface so that the collaborator classes only have to deal with a MessageSender and remain blind to the fact that any sort of low-level socket communication is going on to achieve the sending of that message.

like image 27
matt b Avatar answered Oct 17 '22 09:10

matt b