由於大多講解winsock的代碼都是c++的,而winsock只是一些windows api的使用,為了幫助.net程序員深入的理解winsock2,我把.net下同 步socket的實現代碼拆了出來,簡化了一下,大家有空可以調試一下看看。
注意
1、只能跑在win2000以上的系統
2、只支持tcp協議,
3、支持ipv4
改動
1、去掉計數器、日志等邏輯
2、不支持異步,完成端口模型,等有時間了,把完成端口那部分也拆分出來給大家。
為了不讓本帖太短,貼一些代碼中使用到的winsock函數的原型,大家要想開發高性能的網絡程序,就得去深入理解winsock的那幾個函數, 可以看看《windows網絡編程》的第7、8、9章
OSSOCK#region OSSOCK
[SuppressUnmanagedCodeSecurity]
internal static class OSSOCK
{
[DllImport("ws2_32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
internal static extern SocketError WSAStartup([In] short wVersionRequested, out WSAData lpWSAData);
[DllImport("ws2_32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern SafeCloseSocket.InnerSafeCloseSocket WSASocket([In] AddressFamily addressFamily, [In] SocketType socketType, [In] ProtocolType protocolType, [In] IntPtr protocolInfo, [In] uint group, [In] SocketConstructorFlags flags);
[DllImport("ws2_32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern unsafe SafeCloseSocket.InnerSafeCloseSocket WSASocket([In] AddressFamily addressFamily, [In] SocketType socketType, [In] ProtocolType protocolType, [In] byte* pinnedBuffer, [In] uint group, [In] SocketConstructorFlags flags);
[DllImport("ws2_32.dll", SetLastError = true)]
internal static extern SocketError bind([In] SafeCloseSocket socketHandle, [In] byte[] socketAddress, [In] int socketAddressSize);
[DllImport("ws2_32.dll", SetLastError = true)]
internal static extern SocketError listen([In] SafeCloseSocket socketHandle, [In] int backlog);
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail), DllImport("ws2_32.dll", SetLastError = true)]
internal static extern SocketError ioctlsocket([In] SafeCloseSocket socketHandle, [In] int cmd, [In, Out] ref int argp);
[DllImport("ws2_32.dll", SetLastError = true)]
internal static extern unsafe int recv([In] IntPtr socketHandle, [In] byte* pinnedBuffer, [In] int len, [In] SocketFlags socketFlags);
[DllImport("ws2_32.dll", SetLastError = true)]
internal static extern unsafe int send([In] IntPtr socketHandle, [In] byte* pinnedBuffer, [In] int len, [In] SocketFlags socketFlags);
[DllImport("ws2_32.dll", SetLastError = true)]
internal static extern SocketError shutdown([In] SafeCloseSocket socketHandle, [In] int how);
[DllImport("ws2_32.dll", SetLastError = true)]
internal static extern SocketError setsockopt([In] SafeCloseSocket socketHandle, [In] SocketOptionLevel optionLevel, [In] SocketOptionName optionName, [In] ref int optionValue, [In] int optionLength);
}
#endregion
研究了幾天.net socket裡對IOCP的封裝,發現確實有些復雜,不打算往出拆代碼了,自己理解IOCP的代碼,用平台調用寫一個示例吧。甭 管.net再發展,remoting,wcf啥的,底層還是有限的這麼幾個函數,真的推薦大家好好看看,到時候網絡程序出問題了,抓dump,看調用棧也 知道到底阻塞到哪個API了,為什麼會阻塞。學windbg也就是那幾個命令而已,關鍵你還得了解clr的內部運行機理,win32api,crt,il甚至匯編 等。
本文配套源碼