c# socket 客户端异步实现

简易封装:

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

namespace dclient
{
    public delegate void DelegateMsg(object msg);
    public class Client
    {
        private static Socket _clientSocket;

        private static string _server;
        private static int _port;

        public static DelegateMsg OnConnect;
        public static DelegateMsg OnSend;
        public static DelegateMsg OnReceive;
        public static DelegateMsg OnServerDown;
        public static DelegateMsg OnErr;

        public static void Connect()
        {
            try
            {
                _server = System.Configuration.ConfigurationManager.AppSettings["serverIp"];
                _port = int.Parse(System.Configuration.ConfigurationManager.AppSettings["serverPort"]);

                IPEndPoint ip = new IPEndPoint(IPAddress.Parse(_server), _port);
                _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                _clientSocket.BeginConnect(ip, new AsyncCallback(ConnectCallBack), _clientSocket);
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        private static void ConnectCallBack(IAsyncResult iar)
        {
            Socket client = (Socket)iar.AsyncState;
            try
            {
                client.EndConnect(iar);
                OnConnect("已连接");
            }
            catch (SocketException e)
            {
                if (e.ErrorCode == 10061)
                {
                    OnErr("服务器程序未运行或服务器端口未开放");
                }
                else
                {
                    OnErr(e.Message);
                }
            }
            finally
            {
            }
        }

        public static void Send(string msg)
        {
            if (_clientSocket == null || msg == string.Empty) return;

            msg += "\r\n";

            byte[] data = Encoding.UTF8.GetBytes(msg);
            try
            {
                _clientSocket.BeginSend(data, 0, data.Length, SocketFlags.None, asyncResult =>
                {
                    int length = _clientSocket.EndSend(asyncResult);
                    OnSend(string.Format("客户端发送消息:{0}", msg));
                }, null);
            }
            catch (Exception e)
            {
                OnErr(e.Message);
            }
        }

        public static void Recive()
        {
            byte[] data = new byte[1024];
            try
            {
                _clientSocket.BeginReceive(data, 0, data.Length, SocketFlags.None,
                asyncResult =>
                {
                    try
                    {
                        int length = _clientSocket.EndReceive(asyncResult);
                        OnReceive(string.Format("收到服务器消息:长度:{1},{0}", Encoding.UTF8.GetString(data), length));
                        Recive();
                    }
                    catch (SocketException e)
                    {
                        if (e.ErrorCode == 10054)
                        {
                            OnServerDown("服务器已断线");
                        }
                        else
                        {
                            OnErr(e.Message);
                        }
                    }
                }, null);
            }
            catch (Exception ex)
            {
                OnErr(ex.Message);
            }
        }


    }
}

使用:

  public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Client.OnConnect += new DelegateMsg(connect);
            Client.OnSend += new DelegateMsg(send);
            Client.OnReceive += new DelegateMsg(receive);
            Client.OnServerDown += new DelegateMsg(svrdown);
            Client.OnErr += new DelegateMsg(onerr);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Client.Connect();
        }

        private void connect(object msg)
        {
            System.Diagnostics.Debug.WriteLine(msg.ToString());
            Client.Send("DALO 发送测试");
            Client.Recive();
        }

        private void send(object msg)
        {
            System.Diagnostics.Debug.WriteLine(msg.ToString());
        }

        private void receive(object msg)
        {
            System.Diagnostics.Debug.WriteLine(msg.ToString());
        }

        private void svrdown(object msg)
        {
            System.Diagnostics.Debug.WriteLine(msg.ToString());
        }

        private void onerr(object msg)
        {
            System.Diagnostics.Debug.WriteLine(msg.ToString());
        }
    }

未实现的几个常用操作:
1、接收服务器发送的大数据量的合包。
2、服务器断线后客户端自动检测并重连,需先将_clientSocket释放。
3、心跳包。

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值