这个例子是在帮助文档里面抄的,所以抄出问题了(哭)。
主要是public  void Read_Callback(IAsyncResult ar)里面有些代码不执行,并且我也想不过为什么不执行。
请大家指教
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
namespace ConsoleApplication1
{
    public class StateObject
    {
        public Socket workSocket = null;
        public const int BUFFER_SIZE = 1024;
        public byte[] buffer = new byte[BUFFER_SIZE];
        public StringBuilder sb = new StringBuilder();
    }
    class Program
    {
        static void Main(string[] args)
        {
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect("10.254.254.36", 23);
            StateObject state = new StateObject();
            state.workSocket = socket;
            socket.BeginReceive(state.buffer, 0, StateObject.BUFFER_SIZE, SocketFlags.None, new AsyncCallback(Read_Callback), state);
        }
        public static void Read_Callback(IAsyncResult ar)
        {
            StateObject so = (StateObject)ar.AsyncState;
            Socket s = so.workSocket;
            int read = s.EndReceive(ar);
            if (read > 0)
            {
                so.sb.Append(Encoding.ASCII.GetString(so.buffer, 0, read));
                s.BeginReceive(so.buffer, 0, StateObject.BUFFER_SIZE, 0,
                                         new AsyncCallback(Read_Callback), so);//这里都会执行
            }
            else
            {
                if (so.sb.Length > 1)
                {
                    string strContent;
                    strContent = so.sb.ToString();
                    Console.WriteLine(String.Format("Read {0} byte from socket" +
                                     "data = {1} ", strContent.Length, strContent));//为什么这里永远都不执行了。很奇怪。
                }
                s.Close();
            }
        }
    }
}

解决方案 »

  1.   

    对了,会不会是因为你是static的,我做异步接收的函数都不是用静态的。
      

  2.   

    当read<=0时,才回执行else中的内容,而实际上read只能等于0,我认为是要发送一个内容为“空”的数据包。
    这样可以触发BeginReceive,但EndReceive后read是0,也就走到else去执行了。
      

  3.   

    当你的服务器端对你进行强行的关闭连接的时候你的read就会等于0.
    例如:Socket socket ............int received = socket.Receive(buffer);
    if(received == 0)
    {
      //主机关闭了你的链接.
    }
      

  4.   

    s.BeginReceive(so.buffer, 0, StateObject.BUFFER_SIZE, 0,
                                             new AsyncCallback(Read_Callback), so);//这里都会执行
    是的,确实会执行,不过BeginReceive只有接收到数据以后才会调用AsyncCallback委托来执行如果没有数据传送过来BeginReceive所调用的委托并不会执行
    所以不能在委托中使用int result = Socket.EndReceive(); result = 0 来判断数据传输结束
    你自己在客户端传送数据的时候指定个协议吧,服务器接受的时候判断一下结束标志
      

  5.   

    我的也有这种情况的,但是在BeginReceive()代码下加个send()就可以调用这是为什么