user5858
user5858

Reputation: 1221

Closing websocket immediately after sending message

I'm using https://github.com/websockets/ws

I've a silly question.

Can I do something like this to free resources quickly:

conn.send("otpreceived");
 conn.close();

At the moment I'm doing like this:

conn.send("otpreceived");
setTimeout(function ()
{
conn.close();
}, 2000);

I'm not sure if I can close the websocket immediately after send message

Upvotes: 0

Views: 1197

Answers (1)

Minutia
Minutia

Reputation: 121

Short Answer: Yes you can do this.

Long Answer:

Im going to assume you want to close it immediately for performance gains which is likely negligible. In socket programming, you want to open the socket and keep it open until you are finshed using it.

As you may already know, performing a close() on the connection will require you to open() that connection again if you ever want to send more messages or receieve a response from the other end. Now to answer your question, if you just want to send "otpreceived" without sending anything else or receiving, then yes close it. Otherwise just leave it open until the end of the program.

Now Ive only dealt with socket programming in c but I will say the following... Does it save resources? Yes. Opening and closing sockets is a kernel function, so it accesses low memory components which is abstracted for you. You may not notice a difference in performance depending on many things like what it is your program is doing and how many concurrent connections exist at a given time. So with that said its usually best to keep your connection open until the very end.

Upvotes: 2

Related Questions