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

C# 异步Socket 由于线程退出或应用程序请求,已放弃 I/O 操作。
本人刚接触C#异步Socket编程。当程序执行到int bytesRead = handler.EndReceive(ar)时,就会报错,“由于线程退出或应用程序请求,已放弃 I/O 操作。”不知道是为什么,还请高人指点,谢谢了。
程序如下:服务器端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace TongEx060401
{
  class Program
  {
  private static IPAddress myIP = IPAddress.Parse("172.25.13.51");
  private static IPEndPoint myServer;
  private static Socket mySocket;
  private static Socket handler;
  private static ManualResetEvent myReset = new ManualResetEvent(false);
  static void Main(string[] args)
  {
  Thread threadWatch = null; //负责 调用套接字, 执行 监听请求的线程
  try
  {
  mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //定义套接字;
  myServer = new IPEndPoint(myIP, 6000);
  mySocket.Bind(myServer);
  mySocket.Listen(200);
  Console.WriteLine("启动服务器成功...");
  threadWatch = new Thread(new ThreadStart(target));
  //threadWatch = new Thread(target);
  threadWatch.Start();
  }
  catch (Exception e)
  {
  Console.WriteLine(e.Message);
  }

  }
  private static void target()
  {
  while (true)
  {
  //设为非终止
  //允许继续等待;
  myReset.Reset();
  mySocket.BeginAccept(new AsyncCallback(AcceptCallback), mySocket);
  //阻塞当前线程,直到收到请求信号
  myReset.WaitOne();
  }
  }
  private static void AcceptCallback(IAsyncResult ar)
  {
  //将事件设为终止
  myReset.Set();
  Socket listener = (Socket)ar.AsyncState; //获取用户定义的对象,他限定或包含关于异步操作的信息
  handler = listener.EndAccept(ar);
  //获取状态
  StateObject state = new StateObject();
  state.workSocket = handler;
  Console.WriteLine("与客户建立连接。");
  try
  {
  byte[] byteData = System.Text.Encoding.BigEndianUnicode.GetBytes("已经准备好,请通话!");
  //开始发送数据
  //handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
  }
  catch (Exception ee)
  {
  Console.WriteLine(ee.Message);
  }
  Thread thread = new Thread(new ThreadStart(begReceive));
  thread.Start();
  }
  private static void SendCallback(IAsyncResult ar)
  {
  myReset.Reset();
  try
  {
  handler = (Socket)ar.AsyncState;
  int bytesSent = handler.EndSend(ar);
  }
  catch (Exception eee)
  {
  Console.WriteLine(eee.Message);
  }
  }
  private static void begReceive()
  {
  myReset.Reset();