本帖最后由 bbaibb1009 于 2009-07-20 11:01:20 编辑

解决方案 »

  1.   


       /// <summary>
            /// 监听的工作线程的方法
            /// </summary>
            private void targett()
            {
                Console.WriteLine("开始监听的工作线程:targett()");
                while (CloseFlag)
                {
                    try
                    {
                        if (sock.Connected == true)
                        {
                            //ManualResetEvent复位,将事件状态设置为非终止状态,导致线程阻止。
                            Done.Reset();                        //开始接受连接请求,开始一个异步操作来接受一个传入的连接尝试。AsyncCallback委托的作用 引用在相应异步操作完成时调用的方法。
                            sock.BeginAccept(new AsyncCallback(AcceptCallback), sock);                        //等待信号,暂时阻止线程
                            Done.WaitOne();
                        }
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message, "服务器端:监听方法抛出异常");
                    }
                }        }        private void AcceptCallback(IAsyncResult ar)
            {
                Console.WriteLine("接收回调函数:AcceptCallback(IAsyncResult ar)");
                try
                {
                    //允许线程继续
                    Done.Set();                Socket listener = (Socket)ar.AsyncState;//建立一个监听套接字
                    handler = listener.EndAccept(ar);        //异步接受传入的连接尝试,并创建新的 Socket 来处理远程主机通信。                StateObject state = new StateObject();//建立工作类实例
                    state.workSocket = handler;//这一步标志着客户连接正式建立
                    // statusBarPanel1.Text = "与客户建立连接。";//提示正式建立客户连接
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message, "服务器端:接收回调函数异常");
                }
                try
                {   //发送反馈信息之客户端
                    byte[] byteData = System.Text.Encoding.BigEndianUnicode.GetBytes("准备完毕,可以通话!" + "\n\r");
                    handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);            }
                catch (Exception ee)
                {
                    MessageBox.Show(ee.Message, "服务器端:发送反馈信息异常");
                }
                Thread thread = new Thread(new ThreadStart(rec));//该线程用于读取数据
                thread.Start();        }
            private void rec()
            {
                Console.WriteLine("接收回调函数:rec()");
                try
                {
                    StateObject state = new StateObject();
                    state.workSocket = handler;//handler英文释义:句柄、管理者,异步接受传入的连接尝试                //开始异步接收
                    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message, "服务器端:接收信息异常");
                }        }
            /// <summary>
            /// 异步接收的回调函数
            /// </summary>
            /// <param name="ar"></param>
            private void ReadCallback(IAsyncResult ar)
            {
                Console.WriteLine("接收回调函数:ReadCallback(IAsyncResult ar)");
                try
                {
                    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);//清空字节流
                    rchReceiveMessage.AppendText(content + "\r\n");//显示
                    tt.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);//继续读取
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message, "服务器端:异步接收回调函数异常");
                }        }
            /// <summary>
            /// 发送信息
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void btnSendMessage_Click(object sender, EventArgs e)
            {
                try
                {
                    byte[] byteData = System.Text.Encoding.BigEndianUnicode.GetBytes(txtNickname.Text + ">>>" + rchSendMessage.Text + "\r\n");                //异步发送
                    handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
                }
                catch (Exception ee)
                {
                    MessageBox.Show(ee.Message, "服务器端:发送信息异常");
                }
            }
            /// <summary>
            /// 异步发送的回调方法
            /// </summary>
            /// <param name="ar"></param>
            private void SendCallback(IAsyncResult ar)
            {
                try
                {
                    handler = (Socket)ar.AsyncState;
                    int bytesSent = handler.EndSend(ar);
                }
                catch(Exception e)
                {
                    MessageBox.Show(e.Message + "!", "服务器端:异步发送回调异常");
                }
            }
        }
    }
      

  2.   

    客户端:
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;namespace Client
    {
        public partial class Form1 : Form
        {
            private IPAddress myIP = IPAddress.Parse("127.0.0.1");
            private IPEndPoint MyServer;
            private Socket sock;
            private static ManualResetEvent connectDone = new ManualResetEvent(false);
            private static ManualResetEvent sendDone = new ManualResetEvent(false);
            
            //public delegate void myDelegate(int anInteger, string aString); 
            /// <summary>
            /// 请求连接
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void btnRequestConn_Click(object sender, EventArgs e)
            {
                Console.WriteLine("开始--请求:btnRequestConn_Click(object sender, EventArgs e)");
                try
                {
                    myIP = IPAddress.Parse(txtServerIP.Text);            }
                catch
                {
                    MessageBox.Show("客户端:您输入的IP地址格式不正确,请重新输入!");
                }
                try
                {
                    MyServer = new IPEndPoint(myIP, Int32.Parse(txtPort.Text));
                    sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);                //异步连接请求,利用状态对象传递客户端Socket对象sock
                    sock.BeginConnect(MyServer, new AsyncCallback(ConnectCallback), sock);                //等待信号,阻塞,直到连接成功
                    connectDone.WaitOne();
                }
                catch (Exception ee)
                {
                    MessageBox.Show(ee.Message, "客户端:请求连接异常");
                }
                Console.WriteLine("结束--请求:btnRequestConn_Click(object sender, EventArgs e)");
            }        /// <summary>
            /// 异步连接请求的回调方法
            /// </summary>
            /// <param name="ar"></param>
            private void ConnectCallback(IAsyncResult ar)
            {
                Console.WriteLine("-开始--异步连接请求的回调方法:ConnectCallback(IAsyncResult ar)");
                try
                {
                    //客户端Socket对象
                    Socket client = (Socket)ar.AsyncState;
                    client.EndConnect(ar);
                    try
                    {
                        byte[] byteData = System.Text.Encoding.BigEndianUnicode.GetBytes("准备完毕,可以通话!" + "\n\r");
                        //异步传送数据
                        sock.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), sock);                }
                    catch (Exception ee)
                    {
                        MessageBox.Show(ee.Message, "客户端:异步传送信息核实异常");
                    }                this.toolStripStatusLabel1.Text = "与主机" + txtServerIP.Text + "端口" + txtPort.Text + "建立连接!";                //开始接受数据的线程
                    Thread thread = new Thread(new ThreadStart(targett));
                    thread.Start();                //设置信号,连接成功
                    connectDone.Set();
                }
                catch (Exception e)
                {                MessageBox.Show(e.Message + e.ToString(), "客户端:连接请求回调函数异常");
                    Console.WriteLine(e.Message);
                }
                Console.WriteLine("-结束--异步连接请求的回调方法:ConnectCallback(IAsyncResult ar)");
            }        private void btnSendMessage_Click(object sender, EventArgs e)
            {
                try
                {
                    byte[] byteData = System.Text.Encoding.BigEndianUnicode.GetBytes(txtNickname.Text + ">>>" + rchSend.Text + "\r\n");                //开始异步发送数据
                    sock.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), sock);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "客户端:发送即时信息异常");
                }
            }
            /// <summary>
            /// 异步发送数据的回调函数
            /// </summary>
            /// <param name="ar"></param>
            private void SendCallback(IAsyncResult ar)
            {
                Console.WriteLine("--开始-- 异步发送数据的回调函数:SendCallback(IAsyncResult ar)");
                try
                {
                    Socket client = (Socket)ar.AsyncState;                //设置信号
                    sendDone.Set();
                }
                catch (Exception ee)
                {
                    MessageBox.Show(ee.Message, "客户端:发送数据回调函数异常");
                }            Console.WriteLine("--结束-- 异步发送数据的回调函数:SendCallback(IAsyncResult ar)");
            }
            /// <summary>
            /// 开始接受数据的线程的方法
            /// </summary>
            private void targett()
            {
               
                Console.WriteLine("-开始--开始接受数据的线程的方法:targett()");
                try
                {
                    //实例化一个状态对象,用来传递sock
                    StateObject state = new StateObject();
                    state.workSocket = sock;
                    //开始接收数据,接受到的数据保存在状态对象中
                    sock.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
                    //state.workSocket.BeginReceive(state.buffer, 0, state.buffer.Length, 0, new AsyncCallback(ReceiveCallback), state);            }
                catch (Exception ee)
                {
                    MessageBox.Show(ee.Message, "客户端:接收数据函数异常");
                }            Console.WriteLine("-结束--开始接受数据的线程的方法:targett()");
            }
      

  3.   

    客户端:
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;namespace Client
    {
        public partial class Form1 : Form
        {
            private IPAddress myIP = IPAddress.Parse("127.0.0.1");
            private IPEndPoint MyServer;
            private Socket sock;
            private static ManualResetEvent connectDone = new ManualResetEvent(false);
            private static ManualResetEvent sendDone = new ManualResetEvent(false);
            
            //public delegate void myDelegate(int anInteger, string aString); 
            /// <summary>
            /// 请求连接
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void btnRequestConn_Click(object sender, EventArgs e)
            {
                Console.WriteLine("开始--请求:btnRequestConn_Click(object sender, EventArgs e)");
                try
                {
                    myIP = IPAddress.Parse(txtServerIP.Text);            }
                catch
                {
                    MessageBox.Show("客户端:您输入的IP地址格式不正确,请重新输入!");
                }
                try
                {
                    MyServer = new IPEndPoint(myIP, Int32.Parse(txtPort.Text));
                    sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);                //异步连接请求,利用状态对象传递客户端Socket对象sock
                    sock.BeginConnect(MyServer, new AsyncCallback(ConnectCallback), sock);                //等待信号,阻塞,直到连接成功
                    connectDone.WaitOne();
                }
                catch (Exception ee)
                {
                    MessageBox.Show(ee.Message, "客户端:请求连接异常");
                }
                Console.WriteLine("结束--请求:btnRequestConn_Click(object sender, EventArgs e)");
            }        /// <summary>
            /// 异步连接请求的回调方法
            /// </summary>
            /// <param name="ar"></param>
            private void ConnectCallback(IAsyncResult ar)
            {
                Console.WriteLine("-开始--异步连接请求的回调方法:ConnectCallback(IAsyncResult ar)");
                try
                {
                    //客户端Socket对象
                    Socket client = (Socket)ar.AsyncState;
                    client.EndConnect(ar);
                    try
                    {
                        byte[] byteData = System.Text.Encoding.BigEndianUnicode.GetBytes("准备完毕,可以通话!" + "\n\r");
                        //异步传送数据
                        sock.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), sock);                }
                    catch (Exception ee)
                    {
                        MessageBox.Show(ee.Message, "客户端:异步传送信息核实异常");
                    }                this.toolStripStatusLabel1.Text = "与主机" + txtServerIP.Text + "端口" + txtPort.Text + "建立连接!";                //开始接受数据的线程
                    Thread thread = new Thread(new ThreadStart(targett));
                    thread.Start();                //设置信号,连接成功
                    connectDone.Set();
                }
                catch (Exception e)
                {                MessageBox.Show(e.Message + e.ToString(), "客户端:连接请求回调函数异常");
                    Console.WriteLine(e.Message);
                }
                Console.WriteLine("-结束--异步连接请求的回调方法:ConnectCallback(IAsyncResult ar)");
            }        private void btnSendMessage_Click(object sender, EventArgs e)
            {
                try
                {
                    byte[] byteData = System.Text.Encoding.BigEndianUnicode.GetBytes(txtNickname.Text + ">>>" + rchSend.Text + "\r\n");                //开始异步发送数据
                    sock.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), sock);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "客户端:发送即时信息异常");
                }
            }
            /// <summary>
            /// 异步发送数据的回调函数
            /// </summary>
            /// <param name="ar"></param>
            private void SendCallback(IAsyncResult ar)
            {
                Console.WriteLine("--开始-- 异步发送数据的回调函数:SendCallback(IAsyncResult ar)");
                try
                {
                    Socket client = (Socket)ar.AsyncState;                //设置信号
                    sendDone.Set();
                }
                catch (Exception ee)
                {
                    MessageBox.Show(ee.Message, "客户端:发送数据回调函数异常");
                }            Console.WriteLine("--结束-- 异步发送数据的回调函数:SendCallback(IAsyncResult ar)");
            }
            /// <summary>
            /// 开始接受数据的线程的方法
            /// </summary>
            private void targett()
            {
               
                Console.WriteLine("-开始--开始接受数据的线程的方法:targett()");
                try
                {
                    //实例化一个状态对象,用来传递sock
                    StateObject state = new StateObject();
                    state.workSocket = sock;
                    //开始接收数据,接受到的数据保存在状态对象中
                    sock.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
                    //state.workSocket.BeginReceive(state.buffer, 0, state.buffer.Length, 0, new AsyncCallback(ReceiveCallback), state);            }
                catch (Exception ee)
                {
                    MessageBox.Show(ee.Message, "客户端:接收数据函数异常");
                }            Console.WriteLine("-结束--开始接受数据的线程的方法:targett()");
            }