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

关于一个异步socket的问题
想学学C#里面的同步socket和异步socket,于是下了个例子,虽然有bug不过改改勉强可以用了,可是发现客户端多于一个就会报错
ex.Message = "The IAsyncResult object was not returned from the corresponding asynchronous method on this class.\r\nParameter name: asyncResult"
服务端是异步的,代码如下

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;

namespace WindowsFormsApplication1
{
  public partial class Form1 : Form
  {
  private delegate void threaddelegate();
  byte[] RecvData = new byte[65535];
  Socket serverSocket;
  List <Socket> clientsocketlist=new List<Socket>();
  public Form1()
  {
  InitializeComponent();
  }

  private void button1_Click(object sender, EventArgs e)
  {
  int connectcount = 100;
  serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  IPEndPoint iep = new IPEndPoint(IPAddress.Any,int.Parse(textBox1.Text));
  serverSocket.Bind(iep);
  this.RecieveMsg.AppendText("开始监听.........\n");
  serverSocket.Listen(connectcount);
  serverSocket.BeginAccept(new AsyncCallback(AcceptConn), serverSocket);
  }

  void AcceptConn(IAsyncResult iar)
  {
  try
  {
  Socket listener = (Socket)iar.AsyncState;
  Socket client = listener.EndAccept(iar);
  this.clientsocketlist.Add(client);
  IPAddress ip = ((System.Net.IPEndPoint)client.RemoteEndPoint).Address;

  threaddelegate settext = delegate()
  {
  lock (this.RecieveMsg)
  {
  this.RecieveMsg.AppendText("服务器已连接" + ip.ToString() + "当前连接数"+this.clientsocketlist.Count.ToString());
  }
  };
  this.RecieveMsg.Invoke(settext);

  //开始接受来自该客户端的数据
  client.BeginReceive(RecvData, 0, RecvData.Length, SocketFlags.None, new AsyncCallback(ReceiveData), client);
  //继续接受其他客户端的连接
  listener.BeginAccept(new AsyncCallback(AcceptConn), client);
  }
  catch (Exception ex)
  {
  MessageBox.Show(ex.Message.ToString());
  }
  }
   
  void ReceiveData(IAsyncResult iar)
  {
  string strRecv;
  Socket client = (Socket)iar.AsyncState;
  int recv = client.EndReceive(iar);
  if (recv == 0)
  {
  this.clientsocketlist.Remove(client);
  client.Close();
  }
  else
  {
  threaddelegate settext = delegate()
  {
  lock (this.RecieveMsg)
  {
  string msgs = Encoding.Unicode.GetString(RecvData, 0, recv);
  this.RecieveMsg.AppendText(msgs);
  }