C#中Socket的Send方法即使是在阻塞模式下也会立即返回,查了不少资料,都没什么结果,最后在MSDN找到了答案。
Send的发送默认是不带参数的,其实是写入了本地缓存区,然后基础系统拆分后分批次发送。如果想要实现真正的阻塞,需要使用SocketFlag参数
但SocketFlag参数在baidu和google并没有很多描述,反倒是MSDN有一些详细的例子,现在把代码贴上来,一看便知
// Displays sending with a connected socket // using the overload that takes a buffer, message size, and socket flags. public static int SendReceiveTest3(Socket server) { byte[] msg = Encoding.UTF8.GetBytes("This is a test"); byte[] bytes = new byte[256]; try { // Blocks until send returns. int i = server.Send(msg, msg.Length, SocketFlags.None); Console.WriteLine("Sent {0} bytes.", i); // Get reply from the server. int byteCount = server.Receive(bytes, server.Available, SocketFlags.None); if (byteCount > 0) Console.WriteLine(Encoding.UTF8.GetString(bytes)); } catch (SocketException e) { Console.WriteLine("{0} Error code: {1}.", e.Message, e.ErrorCode); return (e.ErrorCode); } return 0; }