TcpListener/TcpClient异步编程02

服务器代码示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace ASYNServer
{
    class Server
    {
        private TcpListener tcpListener;
        byte[] buffer = new byte[8096];
        public Server()
        {
            tcpListener = new TcpListener(new IPEndPoint(IPAddress.Parse("127.0.0.1"),10001));
            //开启侦听,最多只能连接20个客户端数目
            tcpListener.Start(20);
            tcpListener.BeginAcceptSocket(ClientConnect, tcpListener);
        }
        /// <summary>
        /// 客户端连接
        /// </summary>
        /// <param name="ar"></param>
        private void ClientConnect(IAsyncResult ar)
        {
            try
            {
                TcpListener listener = (TcpListener)ar.AsyncState;
                Socket client = listener.EndAcceptSocket(ar);
                Console.WriteLine(client.RemoteEndPoint.ToString() + "连接成功");
                //侦听结束后开始接收数据
                ReceiveData(client);
                //重新侦听是否有新的客户端连接
                //如果这里不写  那么只能侦听一次
                tcpListener.BeginAcceptSocket(ClientConnect, tcpListener);
            }
            catch (Exception e)
            {

                Console.WriteLine("ClientConnect"+e.Message);
            }
        }
        /// <summary>
        /// 接受数据的回调
        /// </summary>
        /// <param name="client"></param>
        private  void ReceiveData(Socket client)
        {
            SocketError socketError;
            client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, out socketError, ReceiveCallback, client);
        }
        /// <summary>
        /// 一次接收的数据的长度
        /// </summary>
        int receLen = 0;
        private void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                SocketError socketError;
                Socket client = (Socket)ar.AsyncState;
                receLen = client.EndReceive(ar, out socketError);
                if (receLen>0)
                {
                    //处理接收到的数据
                    OnReceiveData(client);
                }else//当receLen<=0的时候表示客户端断开和服务器的连接
                {
                    Console.WriteLine(client.LocalEndPoint.ToString()+"关闭了");
                }
                //重新接受数据
                ReceiveData(client);
            }
            catch (Exception e)
            {
                Console.WriteLine("ReceiveCallback:" + e.Message);
            }
        }
        /// <summary>
        /// 接受数据
        /// </summary>
        /// <param name="socket"></param>
        private void OnReceiveData(Socket socket)
        {
            byte[] data = Encoding.UTF8.GetBytes("接受成功");
            Console.WriteLine("来自客户端的数据是:"+Encoding.UTF8.GetString(buffer,0, receLen));
        }
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="data"></param>
        public void SendData(Socket socket, byte[] data)
        {
            SocketError socketError;
            socket.BeginSend(data, 0, data.Length, SocketFlags.None, out socketError, SendCallBack, socket);//异步发送数据
        }
        /// <summary>
        /// 发送数据的回调
        /// </summary>
        /// <param name="ar"></param>
        private void SendCallBack(IAsyncResult ar)
        {
            SocketError socketError;
            Socket client = (Socket)ar.AsyncState;
            client.EndSend(ar, out socketError);
        }
    }
}

客户端代码示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace ASYNClient
{
    class Client
    {
        private TcpClient tcpclient = null;
        byte[] result;
        public Client()
        {
            tcpclient = new TcpClient();
            //连接服务器
            tcpclient.BeginConnect(IPAddress.Parse("127.0.0.1"), 10001, ConnectCallback, tcpclient);
        }
        /// <summary>
        /// 连接回调
        /// </summary>
        /// <param name="ar"></param>
        private void ConnectCallback(IAsyncResult ar)
        {
            TcpClient client = (TcpClient)ar.AsyncState;
            try
            {
                if (client.Connected)
                {
                    //连接成功
                    client.EndConnect(ar);
                    //开始接受数据
                    ReceiveData(client);

                }
            }
            catch (Exception e)
            {
                Console.WriteLine("ConnectCallback:"+e.Message);
            }
        }
        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="client"></param>
        private void ReceiveData(TcpClient client)
        {
            NetworkStream stream = client.GetStream();

            result = new byte[client.Available];
          
            try
            {
                stream.BeginRead(result, 0, result.Length, ReadCallBack, stream);
            }
            catch (Exception e)
            {
                Console.WriteLine("ReceiveData:"+e.Message );
            }
        }
        /// <summary>
        /// 接受消息回调
        /// </summary>
        /// <param name="ar"></param>
        private void ReadCallBack(IAsyncResult ar)
        {
            NetworkStream stream;
            try
            {
                stream = (NetworkStream)ar.AsyncState;
                stream.EndRead(ar);
            }
            catch (IOException e)
            {
                Console.WriteLine("远程服务器关闭");
                
            }
           
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="data"></param>
        public void SendData(byte[] data)
        {
            if (tcpclient.Connected)
            {
                NetworkStream stream = tcpclient.GetStream();
                stream.BeginWrite(data,0,data.Length, SendCallback, stream);

            }
        }
        /// <summary>
        /// 发送消息回调
        /// </summary>
        /// <param name="ar"></param>
        private void SendCallback(IAsyncResult ar)
        {
            NetworkStream stream = (NetworkStream)ar.AsyncState;
            stream.EndWrite(ar);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值