TCP socket和web socket的區別

i042416發表於2019-02-24

小編先習慣性的看了下某中文百科網站對Web Socket的介紹,覺得很囧。如果大家按照這個答案去參加BAT等網際網路公司的前端開發面試,估計會被鄙視。

TCP socket和web socket的區別

還是讓我們閱讀一些英文材料吧。

讓我們直接看stackoverflow上的原文,然後翻譯:


TCP socket和web socket的區別

原文地址:

https://stackoverflow.com/questions/16945345/differences-between-tcp-sockets-and-web-sockets-one-more-time

這個討論有超過8萬的閱讀量。


TCP socket和web socket的區別

首先我們來閱讀這段有166個讚的回答:


TCP socket和web socket的區別

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裡對套接字的操作是非阻塞操作。

TCP socket和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傳送一個訊息“汪子熙”:

TCP socket和web socket的區別

在偵錯程式裡看到的這個字串作為回撥函式的輸入引數注入到函式體內:

TCP socket和web socket的區別

Chrome開發者工具裡觀察到的WebSocket訊息體:

TCP socket和web socket的區別

下次面試被面試官問到TCP和WebSocket套接字的區別,相信大家應該能夠知道如何回答了。

要獲取更多Jerry的原創文章,請關注公眾號"汪子熙":


TCP socket和web socket的區別


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/24475491/viewspace-2636829/,如需轉載,請註明出處,否則將追究法律責任。

相關文章