TCP socket和web socket的区别
小編先習慣性的看了下某中文百科網站對Web Socket的介紹,覺得很囧。如果大家按照這個答案去參加BAT等互聯網公司的前端開發面試,估計會被鄙視。
還是讓我們閱讀一些英文材料吧。
讓我們直接看stackoverflow上的原文,然后翻譯:
原文地址:
https://stackoverflow.com/questions/16945345/differences-between-tcp-sockets-and-web-sockets-one-more-time
這個討論有超過8萬的閱讀量。
首先我們來閱讀這段有166個贊的回答:
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.
當我們向一個通常的TCP套接字發送一段來自內存buffer中的字節數據時,send系統調用返回的是實際發送的字節數。
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.
如果發送數據的目的方套接字是一個非阻塞套接字或者是對寫操作非阻塞的套接字,那么send返回的已發送字節數可能小于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.
如果是阻塞套接字,兩者會相等,因為顧名思義,如果send系統調用沒有把所有待發送數據全部發送,則API調用不會返回。
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.
而Web socket和TCP socket的區別,從發送的數據來看,不再是一系列字節,而是按照一個完整的"消息體"發送出去的,這個"消息體"無法進一步再分割,要么全部發送成功,要么壓根就不發送,不存在像TCP套接字非阻塞操作那樣出現部分發送的情況。換言之,Web Socket里對套接字的操作是非阻塞操作。
這個區別在維基百科上也有清晰闡述:
Websocket differs from TCP in that it enables a stream of messages instead of a stream of bytes
再來看接收方的區別。
原文:
But there are more important differences on the receiving side of things. When the receiver does a recv (or read) on a TCP socket, there is no guarantee that the number of bytes returned correspond 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 receipt 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.
同理,在TCP套接字的場景下,接收方從TCP套接字讀取的字節數,并不一定等于發送方調用send所發送的字節數。而WebSocket呢?WebSocket的接收方從套接字讀取數據,根本不是像TCP 套接字那樣直接用recv/read來讀取, 而是采取事件驅動機制。即應用程序注冊一個事件處理函數,當web socket的發送方發送的數據在接收方應用從內核緩沖區拷貝到應用程序層已經處于可用狀態時 ,應用程序注冊的事件處理函數以回調(callback)的方式被調用。
看個例子:
我通過WebSocket發送一個消息“汪子熙”:
在調試器里看到的這個字符串作為回調函數的輸入參數注入到函數體內:
Chrome開發者工具里觀察到的WebSocket消息體:
下次面試被面試官問到TCP和WebSocket套接字
的區別,相信大家應該能夠知道如何回答了。
要獲取更多Jerry的原創文章,請關注公眾號"汪子熙":
總結
以上是生活随笔為你收集整理的TCP socket和web socket的区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 快讯|360宣布基于大模型的360智脑开
- 下一篇: Jerry的SAP One Order框