Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Network Programming: to maintain sockets or not?

I'm currently translating an API from C# to Java which has a network component.

The C# version seems to keep the input and output streams and the socket open for the duration of its classes being used.

Is this correct?

Bearing in mind that the application is sending commands and receiving events based on user input, is it more sensible to open a new socket stream for each "message"?

I'm maintaining a ServerSocket for listening to the server throwing events but I'm not so sure that maintaining a Socket and output stream for outbound comms is such a good idea.

I'm not really used to Socket programming. As with many developers I usually work at the application layer when I need to do networking and not at the socket layer, and it's been 5 or 6 years since I did this stuff at university.

Cheers for the help. I guess this is more asking for advice than for a definitive answer.

like image 609
Omar Kooheji Avatar asked Feb 06 '09 10:02

Omar Kooheji


1 Answers

There is a trade off between the cost of keeping the connections open and the cost of creating those connections.

Creating connections costs time and bandwidth. You have to do the 3-way TCP handshake, launch a new server thread, ...

Keeping connections open costs mainly memory and connections. Network connections are a resource limited by the OS. If you have too many clients connected, you might run out of available connections. It will cost memory as you will have one thread open for each connection, with its associated state.

The right balanced will be different based on the usage you expect. If you have a lot of clients connecting for short period of times, it's probably gonna be more efficient to close the connections. If you have few clients connecting for long period of time, you should probably keep the connections open ...

like image 83
Guillaume Avatar answered Sep 24 '22 06:09

Guillaume