I don't understand ports and sockets in Node.js

Hi,

Can someone please give me an explanation as to what ports and sockets, in addition to how they are alike and different.

The port number that you listen to when you create a server seems random to me. Is this number just arbitrary? I did the node.js tutorials from the back-end section and understand most of it. I just don’t know what the deal is with the random assignment of port numbers.

Please enlighten me

-Andres

4 Likes

Great question. I’ll take a stab at this, though I’m no expert.

Port - Are endpoints of communication; on the server-side we have our listener. Valid port numbers can be 1 through 65535, but we a lot of the lower numbers are defaulted to certain processes. From what I’ve seen, people tend to use higher numbers like 3000, 5000, 8000 and 8080, but most of the time it doesn’t seem to matter what the number is if you’re working on your own stuff, but it’s a good idea to console.log that port number in the listen method so you remember which localhost to navigate to.

Socket - Are endpoint instances that are bound to a port and have other identifiers like IPs. A socket is one endpoint of a two-way communication link between two programs running on the network. A single port can have many sockets.

Yes, the port number you listen to is pretty arbitrary.
JavaScript and node.js are single-threaded and processes things asynchronously based on events. Per the website “Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient.” Non-blocking is important, because we don’t one process “blocking”/taking up the entire thread to complete (definitely would have scalability and performance issues). Tying this back to sockets, one of the Stack Overflow links below explains this:
“When a server’s processes listening to a port that means multiple sockets can simultaneously connect and communicate with the same server-process. If a server uses only a single child-process to serve all the sockets then the server is called single-process/threaded and if the server uses many sub-processes to serve each socket by one sub-process then the server is called multi-process/threaded server.” [1]


http://docs.oracle.com/javase/tutorial/networking/sockets/definition.html has a diagram that may be helpful

https://stackoverflow.com/questions/3329641/how-do-multiple-clients-connect-simultaneously-to-one-port-say-80-on-a-server (particularly the second answer that has 248 upvotes right now, by KGhatak) [1]

3 Likes

Thanks for your explanation, I’m starting to wrap my head around it