Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do WebSocket keep connection

Tags:

websocket

It says websocket

" Communication takes place over single TCP socket using the ws (unsecure) or wss (secure) protocol..."

Does it mean client-server only need one handshake? But I saw handshakes in NodeJs console every second. What are they?

like image 300
EasonBlack Avatar asked Jun 28 '26 18:06

EasonBlack


1 Answers

A handshake needs to be done whenever a websocket-using javascript is executed by a user. Websockets can not be reused between page accesses. They are closed automatically when the user closes or leaves the page. When the user opens a new tab, a second socket will be created which will need a new handshake.

When your NodeJs application is a web application where the client lives on a HTML page, the connection will be re-established whenever the user requests the page. So when the user navigates through your website and there is a websocket-using javascript embedded on each HTML page, then you will see a new handshake being performed after every click.

When you see new handshakes all the time although there is only one user who stays on the same page all the time, then there might indeed be something wrong with your application. Does it maybe create new sockets all the time although it could reuse an existing one? (every new WebSocket means one new websocket connection means one new handshake being performed).

like image 63
Philipp Avatar answered Jul 03 '26 02:07

Philipp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!