首页 > 编程开发 > Objective-C编程 >
-
c#使用winsock api 实现同步 socket服务器
由于大多讲解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甚至汇编等。