What is the fundamental difference between WebSockets and pure TCP?

Technology CommunityCategory: WebSocketsWhat is the fundamental difference between WebSockets and pure TCP?
VietMX Staff asked 3 years ago
Problem

I’ve read about WebSockets and I wonder why browser couldn’t simply open trivial TCP connection and communicate with server like any other desktop application?

  • It’s easier to communicate via TCP sockets when you’re working within an intranet boundary, since you likely have control over the machines on that network and can open ports suitable for making the TCP connections.
  • Over the internet, you’re communicating with someone else’s server on the other end. They are extremely unlikely to have any old socket open for connections. Usually they will have only a few standard ones such as port 80 for HTTP or 443 for HTTPS. So, to communicate with the server you are obliged to connect using one of those ports.
  • Given that these are standard ports for web servers that generally speak HTTP, you’re therefore obliged to conform to the HTTP protocol, otherwise the server won’t talk to you. The purpose of web sockets is to allow you to initiate a connection via HTTP, but then negotiate to use the web sockets protocol (assuming the server is capable of doing so) to allow a more “TCP socket”-like communication stream.
  • A WebSocket requires some sort of transport protocol to operate over, but that transport layer doesn’t have to be TCP (it’s almost always going to be TCP in practice though). You could think of WebSockets as a kind of wrapper around TCP, but I don’t believe there’s any prescriptive link between the two.
  • When you send bytes from a buffer with a normal TCP socket, the send function returns the number of bytes of the buffer that were sent. If it is a non-blocking socket or a non-blocking send then the number of bytes sent may be less than the size of the buffer. If it is a blocking socket or blocking send, then the number returned will match the size of the buffer but the call may block. With WebSockets, the data that is passed to the send method is always either sent as a whole “message” or not at all. Also, browser WebSocket implementations do not block on the send call.
  • When the receiver does a recv (or read) on a TCP socket, there is no guarantee that the number of bytes returned corresponds to a single send (or write) on the sender side. It might be the same, it may be less (or zero) and it might even be more (in which case bytes from multiple send/writes are received). With WebSockets, the recipient of a message is event-driven (you generally register a message handler routine), and the data in the event is always the entire message that the other side sent.