1. 程式人生 > >提醒初學者注意 send(sendto) recv(recvfrom) 中的 引數flags

提醒初學者注意 send(sendto) recv(recvfrom) 中的 引數flags

/*

說明:

    1 這篇文章是給象我一樣的初學者看的,如果您有一些經驗了,請不要看,因為它會花費您寶貴的時間。 

    2 使用 MSDN 版本:MSDN Library - October 2001

*/

第一次寫這個玩意,感覺很新鮮。

也希望這件事(寫文件)對我和大家有好處。

因為在開發的過程中出現一些彎路,後來發現了。想提醒大家注意。

剛開始接觸 winsock 程式設計是2002-11-30,買的是《Visual C++ 6.0 網路程式設計實作教程》這本書(我個人認為這是一本很好的 winsock 程式設計的書,她很適合初學者),

剛開始使用 winsock 的時候, 是用CAsyncSocket這個類,在 Send and Recvive的時候,nFlags

都有預設的值 0 , 所以沒有引起重視。

virtual int Send( const void* lpBuf, int nBufLen, int nFlags = 0 );

CAsyncSocket::Receive

virtual int Receive( void* lpBuf, int nBufLen, int nFlags = 0 );

*/

並且使用的還比較順手,沒有大的毛病出現。

到了後期,因為我自己想要嘗試不同的東西,想要自己使用自己的CMySocket類,封裝winsock  api,(一直以來我也喜歡自己封裝比較底層的東西,感覺好一些)。

問題來了,在封裝的過程中,我檢視MSDN

/*

int send (
  SOCKET s,             
  const char FAR * buf, 
  int len,              
  int flags             
);
 
The flags parameter can be used to influence the behavior of the function beyond the options specified for the associated socket. The semantics of this function are determined by the socket options and the flags parameter. The latter is constructed by or-ing the following values:

Value Meaning
MSG_DONTROUTE Specifies that the data should not be subject to routing. A
               Windows Sockets service provider can choose to ignore this
               flag.

MSG_OOB Send out-of-band data (stream-style socket such as SOCK_STREAM
        only. Also see DECnet Out-Of-band data for a discussion of this
        topic).

*/

/*我個人是這樣翻譯的:

flags 引數可以影響和(本地 socket)相關聯的遠端 socket 的行為,socket 選項和 flags 引數決定了這個函式(send函式)的功能。後者(flags 引數)可以是以下值的 或(|)。

值的意義
MSG_DONTROUTE 表明(所傳送的)資料不應該通過 routing,windows socket service provider可以選擇忽略這個標誌

(《Windows網路程式設計技術》P141 裡面是這樣說的:MSG_DONTROUTE標誌要求傳送層不要將它發出的包路由出去,由基層的傳送決定是否實現這一請求)


MSG_OOB 傳送 OOB data(比如 流形式的 socket,僅有SOCK_STREAM適用 ,也可以參看DECnet 關於Out-Of-band data這個主題的討論)

*/

在send時,我選了MSG_DONTROUTE標誌,因為我沒有帶外資料啊,(我以為只能有這麼兩個值可以填進去啊!)

在recv時,我選了MSG_PEEK。

結果我在recv的時候得不到正確的結果,還不知道為什麼錯。

查了一個上午,哈哈,終於知道是標誌的設定問題。

我現在把他們設定為 0 。
工作的很好了。

你們也有遇到這樣的問題嗎?
給象我一樣的初學者提個醒。