日期:2014-05-18  浏览次数:20987 次

c# socket异步通信
下面是我的c# socket异步接受发送数据的代码?第一次发送请求的时候,send数据是成功的,当客户端点击按钮再次请求时,就会报“不可访问已释放资源”,有谁可不可以帮我修改一下啊,(客户端会发送很多次请求)
 public class StateObject
  {
  public Socket workSocket = null;

  public const int BufferSize = 1024;

  public byte[] buffer = new byte[BufferSize];

  public StringBuilder sb = new StringBuilder();
  }

  public class AsynchronousSocketListener
  {
  public static Thread mythread; //监听数据
  public static Thread mythreadReceive; //为每个用户创建新的进程

  public static IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
  public static IPAddress ipAddress = ipHostInfo.AddressList[0];
  public static string data = null;

  public static ManualResetEvent allDone = new ManualResetEvent(false);

  public AsynchronousSocketListener()
  {
  }

  public static void StartListening()
  {

  ipHostInfo = Dns.Resolve(Dns.GetHostName());
  ipAddress = ipHostInfo.AddressList[0];



  IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 843);

  Socket listener = new Socket(AddressFamily.InterNetwork,

  SocketType.Stream, ProtocolType.Tcp);
  try
  {
  listener.Bind(localEndPoint);
  listener.Listen(0);
  while (true)
  {

  allDone.Reset();
  Console.WriteLine("Waiting for a connection...");

  listener.BeginAccept(
  new AsyncCallback(AcceptCallback),
  listener);
  allDone.WaitOne();
  }

  }
  catch (Exception e)
  {
  Console.WriteLine(e.ToString());
  }
  // Console.WriteLine("Press ENTER to continue...");
  // Console.Read();

  }


  public static void AcceptCallback(IAsyncResult ar)
  {
  allDone.Set();
  Socket listener = (Socket)ar.AsyncState;
  Socket handler = listener.EndAccept(ar);
   
  StateObject state = new StateObject();
  state.workSocket = handler;


  handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
  new AsyncCallback(ReadCallback), state);
  }

  public static void ReadCallback(IAsyncResult ar)
  {
  String content = String.Empty;
  StateObject state = (StateObject)ar.AsyncState;
  Socket handler = state.workSocket;

  int bytesRead = handler.EndReceive(ar);
  if (bytesRead > 0)
  {
  state.sb.Append(Encoding.ASCII.GetString(
  state.buffer, 0, bytesRead));