TCP和UDP的Client-Server交互流程

1.TCP Client-Server交互流程

2.UDP Client-Server交互流程

注:圖片來源(https://www.cs.dartmouth.edu/~campbell/cs60/socketprogramming.html#x1-100013)。

3.深入挖掘一

TCP是面向連接的協議,也就是說server和client之間發送/接收數據之前,需先建立連接。
因此,TCP的server需依次調用以下函數:

listen() :使一個綁定的TCP套接字的TCP狀態由CLOSE轉至LISTEN。它將sockfd引用的套接字標記爲被動套接字(passive socket),該套接字使用accept()接受傳入的連接請求。

accept():它在偵聽套接字sockfd的掛起連接隊列上提取第一個連接請求,創建一個新的連接套接字,並返回一個引用該套接字的新文件描述符。 新創建的套接字未處於偵聽狀態。原始套接字sockfd不受此調用的影響。

TCP的client需調用以下函數:
connect() :爲一個套接字分配一個自由的本地端口號,並試圖獲得一個新的TCP連接。

而作爲無連接的UDP協議,則不需要上述三個函數。

注:參考文章(https://en.wikipedia.org/wiki/Berkeley_sockets)。

4.深入挖掘二

關於accept()函數,微軟的API指南中有非常詳細的一段描述:

The accept function extracts the first connection on the queue of pending connections on socket s. It then creates and returns a handle to the new socket. The newly created socket is the socket that will handle the actual connection; it has the same properties as socket s, including the asynchronous events registered with the WSAAsyncSelect or WSAEventSelect functions.

The accept function can block the caller until a connection is present if no pending connections are present on the queue, and the socket is marked as blocking. If the socket is marked as nonblocking and no pending connections are present on the queue, accept returns an error as described in the following. After the successful completion of accept returns a new socket handle, the accepted socket cannot be used to accept more connections. The original socket remains open and listens for new connection requests.

The parameter addr is a result parameter that is filled in with the address of the connecting entity, as known to the communications layer. The exact format of the addr parameter is determined by the address family in which the communication is occurring. The addrlen is a value-result parameter; it should initially contain the amount of space pointed to by addr; on return it will contain the actual length (in bytes) of the address returned.

The accept function is used with connection-oriented socket types such as SOCK_STREAM. If addr and/or addrlen are equal to NULL, then no information about the remote address of the accepted socket is returned.

5.深入挖掘三
下面兩個討論,是非常有意思的參考。
(1)https://stackoverflow.com/questions/489036/how-does-the-socket-api-accept-function-work?rq=1
(2)https://stackoverflow.com/questions/774571/server-vs-client-socket-low-level-details

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章