user2740741
user2740741

Reputation: 109

Should I use a WebSocket or a normal TCP Socket?

I am developing a web application that has a desktop client written in Java. I am using WebSockets to communicate between the NodeJS server and the web client.

I am trying to decide whether to use a WebSocket or a normal TCP socket to communicate between the NodeJS server and the desktop client.

As I understand it, it would be easier to use a WebSocket but also a little bit heavier weight.

How does one make this decision?

Upvotes: 4

Views: 9619

Answers (2)

Steffen Ullrich
Steffen Ullrich

Reputation: 123639

It depends on your exact use case:

  • WebSockets are established by first doing a HTTP connection and then upgrading this to the WebSocket protocol. Thus the overhead needed to exchange the first message considerably higher than with simple sockets. But if you just keep the connection open and exchange all messages through a single established socket then this does not matter much.
  • There is a small performance overhead because of the masking. But these are mainly simple computations (XOR) so they should not matter much.
  • It takes a little bit more bandwidth because of the framing. But this should not really matter much.
  • On the positive side it works much better (but not always perfect) together with existing firewalls and proxies so it integrates easier into existing infrastructures. You can also use it more easily with TLS because this is just WebSocket upgrade inside HTTPS instead of inside HTTP.

Thus if you must integrate into existing infrastructure with firewalls and proxies then WebSockets might be the better choice. If your application is performance heavy and needs every tiny bit of bandwidth, processor time and the lowest (initial) latency then plain sockets are better.

Apart from that if latency is really a problem (like with real time audio) then you might better not use any TCP based protocol, like TCP sockets or WebSockets. In this case it might be better to use UDP and deal with the potential packet loss, reordering and duplication inside your application.

Upvotes: 13

Philipp
Philipp

Reputation: 69773

Is there a proper WebSocket library for whatever technology you implement the desktop client in? The websocket protocol is not trivial and it's a rather new technology which is not universally supported yet. When you have to implement WebSocket from scratch using pure TCP/IP sockets you can plan to spend a few days until you have the basic protocol implementation working and can start to implement your own protocol on top of it (been there, done that, threw it away the moment a library was available which worked better than my own implementation).

But if you can find a Websocket implementation for your desktop client, then you could save some work and complexity on the server-side by having both the website and the desktop client communicate with the node.js backend in the same way.

Upvotes: 1

Related Questions