http://www.csdn.net/cnshare/soft/19/19047.shtm

解决方案 »

  1.   

    在socket 里的beginAccept() endAccept()....都是用来异步通信的
    只要它的方法开头用了begin 和End这两个词
      

  2.   

    关于异步通信的实现方式(题目太大),任何一种实现方式都可以写一本书了:1、多线程(Thread)服务端的开销大2、异步委托(Delegate、BeginInvoke)简单,使用范围小3、消息队列(Messaging Queue)编程难度大,不易调试
      

  3.   

    //开始监听
    private void btnListen_Click(object sender, System.EventArgs e)
    {
    try
    {
    IPHostEntry myHost = new IPHostEntry();
    myHost = Dns.GetHostByName(txtServer.Text);
    string IPstring = myHost.AddressList[0].ToString();
    myIP = IPAddress.Parse(IPstring);
    }
    catch
    {
    MessageBox.Show("您输入的IP地址格式不正确,请重新输入!");
    } try
    {
    myServer = new IPEndPoint(myIP,Int32.Parse(txtPort.Text.Trim()));
    mySocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
    mySocket.Bind(myServer);
    mySocket.Listen(50); //IPEndPoint aaIP = (IPEndPoint)mySocket.LocalEndPoint;
    //int aa = aaIP.Port;
    //MessageBox.Show(aa.ToString()); txtState.AppendText("主机"+txtServer.Text+"端口"+txtPort.Text+"开始监听.....\r\n"); //线程
    Thread thread = new Thread(new ThreadStart(target));
    thread.Start();
    }
    catch(Exception ee)
    {
    txtState.AppendText(ee.Message+"\r\n");
    }
    } //线程同步方法target
    private void target()
    {
    while(true)
    {
    //设为非终止
    myReset.Reset(); mySocket.BeginAccept(new AsyncCallback(AcceptCallback),mySocket); //阻塞当前线程,直到收到请求信号
    myReset.WaitOne();
    }
    } //异步回调方法AcceptCallback
    private void AcceptCallback(IAsyncResult ar)
    {
    //将事件设为终止
    myReset.Set(); Socket listener = (Socket)ar.AsyncState;
    handler = listener.EndAccept(ar); //获取状态
    StateObject state = new StateObject();
    state.workSocket = handler; txtState.AppendText("与客户建立连接。\r\n"); try
    {
    byte[] byteData = System.Text.Encoding.BigEndianUnicode.GetBytes("已经准备好,请通话!"+"\r\n");
    //开始发送
    handler.BeginSend(byteData,0,byteData.Length,0,new AsyncCallback(SendCallback),handler);
    }
    catch(Exception ee)
    {
    MessageBox.Show(ee.Message);
    } //线程
    Thread thread = new Thread(new ThreadStart(begReceive));
    thread.Start();
    } //异步回调方法 SendCallback
    private void SendCallback(IAsyncResult ar)
    {
    try
    {
    handler = (Socket)ar.AsyncState;
    int bytesSent = handler.EndSend(ar);
    }
    catch(Exception ee)
    {
    MessageBox.Show(ee.Message);
    }
    } //线程同步方法begReceive
    private void begReceive()
    {
    StateObject state = new StateObject();
    state.workSocket = handler;
    handler.BeginReceive(state.buffer,0,StateObject.BufferSize,0,new AsyncCallback(ReadCallback),state);
    } //异步回调方法ReadCallback
    private void ReadCallback(IAsyncResult ar)
    {
    StateObject state = (StateObject) ar.AsyncState;
    Socket tt = state.workSocket; //结束读取并获取读取字节数
    int bytesRead = handler.EndReceive(ar);
    state.sb.Append(System.Text.Encoding.BigEndianUnicode.GetString(state.buffer,0,bytesRead));
    string content = state.sb.ToString();
    state.sb.Remove(0,content.Length);
    rtbIncept.AppendText(content+"\r\n"); //重新开始读取数据
    tt.BeginReceive(state.buffer,0,StateObject.BufferSize,0,new AsyncCallback(ReadCallback),state);
    }#endregion 监听 //发送信息
    private void btnSend_Click(object sender, System.EventArgs e)
    {
                try
    {
    byte[] byteData = System.Text.Encoding.BigEndianUnicode.GetBytes(rtbSend.Text+"\r\n"); //开始发送数据
    handler.BeginSend(byteData,0,byteData.Length,0,new AsyncCallback(SendCallback),handler);
    }
    catch(Exception ee)
    {
    MessageBox.Show(ee.Message);
    }
    } //停止监听
    private void btnStop_Click(object sender, System.EventArgs e)
    {
    try
    {
    mySocket.Close();
    txtState.AppendText("主机"+txtServer.Text+"端口"+txtPort.Text+"停止监听"+"\r\n");
    }
    catch
    {
    MessageBox.Show("监听尚未开始,关闭无效!");
    }
    }
      

  4.   

    首先要用ManualEventReset类来同步将要产生的不同线程 用Set()和Reset()方法来设置和重置它的状态 用WaitOne()方法使主线程等待用BeginConnect()方法连接到服务器,参数中实现一个AsyncCallback委托的回调方法
    sClient.BeginConnect(endPoint,new AsyncCallback(ConnectCallback),sClient);下面是委托方法
    public static void ConnectCallback(IAsyncResult ar)
    {
       //...   sClient.EndConnect(ar); //完成异步请求
       ConnectDone.Set();//调用ManualResetEvent的Set()方法,返回主线程
    }发送接收 形式基本同上
    BeginSend(); EndSend();
    BeginReceive; EndReceive();
      

  5.   

    下面是客户端代码,上面我已做过简要解释了
    using System;
    using System.Net.Sockets;
    using System.Net;
    using System.Text;
    using System.Threading;public class AsyncClient
    {   public static ManualResetEvent ConnectDone = new ManualResetEvent(false);
       public static ManualResetEvent SendDone = new ManualResetEvent(false);
       public static ManualResetEvent ReceiveDone = new ManualResetEvent(false);
          
       public static String response = String.Empty;   
       
       public static String sb = String.Empty;
       
       public static byte[] buffer = new byte[1024];
             
       public static void ConnectCallback(IAsyncResult ar)
       {
          Thread thr = Thread.CurrentThread;
          Console.WriteLine("ConnectCallback Thread State:" + thr.ThreadState);
          
          Socket sClient = (Socket) ar.AsyncState;      sClient.EndConnect(ar);
          
          Console.WriteLine("Socket connected to {0}", sClient.RemoteEndPoint.ToString());
          ConnectDone.Set();   
       }
       
       public static void SendCallback(IAsyncResult ar)
       {
          Thread thr = Thread.CurrentThread;
          Console.WriteLine("SendCallback Thread State:" + thr.ThreadState);
          
          Socket sClient = (Socket) ar.AsyncState;
          
          int bytesSent = sClient.EndSend(ar);
          
          Console.WriteLine("Sent {0} bytes to server.", bytesSent);
          
          SendDone.Set();   
       }
       
       public static void ReceiveCallback(IAsyncResult ar)
       {
          
          Thread thr = Thread.CurrentThread;
          Console.WriteLine("ReceiveCallback Thread State:" + thr.ThreadState);
          
          Socket sClient = (Socket) ar.AsyncState;
          
          int bytesRead = sClient.EndReceive(ar);
          
          if (bytesRead > 0)
          {         
             sb += Encoding.ASCII.GetString(buffer, 0 , bytesRead);
             
             sClient.BeginReceive(buffer, 0 , buffer.Length ,0 , 
                                  new AsyncCallback(ReceiveCallback), sClient);
          }
          else
          {         
             ReceiveDone.Set();
          }
       }
          
       public static void Main(string [] arg)
       {
          try
          {
          
          Thread thr = Thread.CurrentThread;
          Console.WriteLine("Main Thread State:" + thr.ThreadState);
          
             IPHostEntry ipHost = Dns.Resolve("127.0.0.1");
             IPAddress ipAddr = ipHost.AddressList[0];
             IPEndPoint endPoint = new IPEndPoint(ipAddr, 11000);
             
             Socket sClient = new Socket(AddressFamily.InterNetwork, 
                                         SocketType.Stream, ProtocolType.Tcp);
             
             sClient.BeginConnect(endPoint, new AsyncCallback(ConnectCallback), 
                                  sClient);
             
             ConnectDone.WaitOne();
             
              string data = "This is a test.";
     
     for (int i=0;i<72;i++)
       data += i.ToString()+":" + (new string('=',i));
       
       
             byte[] byteData = Encoding.ASCII.GetBytes(data+"<TheEnd>");     
             sClient.BeginSend(byteData, 0 , byteData.Length, 0 , 
                               new AsyncCallback(SendCallback), sClient);
             
             
              for (int i=0;i<5;i++)
              {
              
                   Console.WriteLine(i);
                   Thread.Sleep(10);
              }
              
             
             SendDone.WaitOne();
                   
             sClient.BeginReceive(buffer, 0  , buffer.Length, 0, 
                                  new AsyncCallback(ReceiveCallback), sClient);
             ReceiveDone.WaitOne();         
             
             Console.WriteLine("Response received: {0} ", sb);
             
             sClient.Shutdown(SocketShutdown.Both);
             sClient.Close();         
          }
          catch(Exception e)
          {
             Console.WriteLine(e.ToString());
          }
       }
       
    }
      

  6.   

    下面是服务器端代码
    using System;
    using System.Net.Sockets;
    using System.Net;
    using System.Text;
    using System.Threading;public class AsyncServer
    {
       // buffer to receive and send data
       public static byte[] buffer = new byte[1024];
       
       // the event class to support synchronization
       public static ManualResetEvent socketEvent = new ManualResetEvent(false);
          
       public static void Main(string [] args)
       {
          
          Console.WriteLine("Main Thread ID:" + AppDomain.GetCurrentThreadId());
          
          byte[] bytes = new byte[1024];
       
          IPHostEntry ipHost = Dns.Resolve("127.0.0.1");
          IPAddress ipAddr = ipHost.AddressList[0];
          
          IPEndPoint localEnd = new IPEndPoint(ipAddr, 11000);
          
          Socket sListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
          ProtocolType.Tcp);
          
          
          // binding a socket
          sListener.Bind(localEnd);
             
          // start listening 
          sListener.Listen(10);
             
          Console.WriteLine("Waiting for a connection...");
          
          AsyncCallback aCallback = new AsyncCallback(AcceptCallback);
       
      
       
          // asychronous funtion for accepting connections         
          sListener.BeginAccept( aCallback,sListener);
                
          // waiting for the other threads to finish
          socketEvent.WaitOne();
       
       }
       
       public static void AcceptCallback(IAsyncResult ar)
       {
          Console.WriteLine("AcceptCallback Thread ID:" + AppDomain.GetCurrentThreadId());
           
           // retrieved the socket
          Socket listener = (Socket)ar.AsyncState;
          // new socket 
          Socket handler = listener.EndAccept(ar);
       
          handler.BeginReceive(buffer, 0 , buffer.Length, 0, new AsyncCallback(ReceiveCallback), handler);
       }
       
       public static void ReceiveCallback(IAsyncResult ar)
       {      
          Console.WriteLine("ReceiveCallback Thread ID:" + AppDomain.GetCurrentThreadId());
          
          String content = String.Empty;
          
          Socket handler = (Socket) ar.AsyncState;
          
          int bytesRead = handler.EndReceive(ar);
          
          // if there is some data ..
          if (bytesRead > 0)
          {
             // append it to the main string
             content += Encoding.ASCII.GetString(buffer, 0, bytesRead); 
       
             // if we encounter the end of message character ... 
             if (content.IndexOf(".") > -1)
             {
                Console.WriteLine("Read {0} bytes from socket. \n Data: {1}",content.Length, content);
                byte[] byteData = Encoding.ASCII.GetBytes(content);
          
                // send the data back to the client
                handler.BeginSend(byteData, 0 , byteData.Length, 0 , new AsyncCallback(SendCallback), handler);      
             }
             else
             {
                // otherwise receive the remaining data
                handler.BeginReceive(buffer, 0 , buffer.Length, 0, new AsyncCallback(ReceiveCallback), handler);
             }
          }
       }
       
       public static void SendCallback(IAsyncResult ar)
       {
          Console.WriteLine("SendCallback Thread ID:" + AppDomain.GetCurrentThreadId());
          
          Socket handler = (Socket) ar.AsyncState;
          
          // send data back to the client
          int bytesSent = handler.EndSend(ar);
             
          Console.WriteLine("Sent {0} bytes to Client.", bytesSent);
             
          // close down socket
          handler.Shutdown(SocketShutdown.Both);
          handler.Close();
          
          // set the main thread's event 
          socketEvent.Set();
       }
       
    }
      

  7.   

    上面的例子我是摘自<<.Net网络高级编程>>上的,完整,简明扼要,应该很容易看懂的
      

  8.   

    magamga還不結貼不是有代碼了嗎!http://www.dapha.net/down/download.asp?downid=1&id=1759