服务器异步客户端

服务器

//泛型单例

internal class Singleton<T>where T:class,new()
{
    private static T ins;
    public static T Ins
    {
        get
        {
            if(ins == null)
            {
                ins = new T();
            }
            return ins;
        }
    }
}

//消息中心

internal class MessageManager<T>:Singleton<MessageManager<T>>
{
    Dictionary<int, Action<T>> MsgDic = new Dictionary<int, Action<T>>();
    public void OnAddListen(int id,Action<T> action)
    {
        if(MsgDic.ContainsKey(id))
        {
            MsgDic[id] += action;
        }
        else
        {
            MsgDic.Add(id, action);
        }
    }
    public void OnBroadCast(int id,T t)
    {
        if(MsgDic.ContainsKey(id))
        {
            MsgDic[id](t);
        }
    }
}

internal class Client
{
    public Socket socket;
    public byte[] data=new byte[1024];
}

internal class MsgData
{
    public Client cli;
    public byte[] data;
}

//服务器框架

internal class NetManager:Singleton<NetManager>
{
    Socket socket;
    //public List<Client> allcli=new List<Client>();
    public void InitServer()
    {
        socket=new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        socket.Bind(new IPEndPoint(IPAddress.Any,2201));
        socket.Listen(10);
        Console.WriteLine("2201 服务器开启");
        socket.BeginAccept(OnAccept, null);
    }

    private void OnAccept(IAsyncResult ar)
    {
        try
        {
            Socket socket_cli=socket.EndAccept(ar);
            IPEndPoint iPEnd=socket_cli.RemoteEndPoint as IPEndPoint;
            Console.WriteLine("IP"+iPEnd.Address+"port"+iPEnd.Port+"连接上了");
            socket.BeginAccept(OnAccept, null);
            Client client=new Client();
            client.socket= socket_cli;
            //allcli.Add(client);
            client.socket.BeginReceive(client.data, 0, client.data.Length, SocketFlags.None, Receive, client);

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
    }

    private void Receive(IAsyncResult ar)
    {
        try
        {
            Client client=ar.AsyncState as Client;
            int len=client.socket.EndReceive(ar);
            if(len>0)
            {
             
                byte[] rdata=new byte[len];
                Buffer.BlockCopy(client.data,0,rdata,0,len);
                while(rdata.Length>4)
                {
                    int bodylen=BitConverter.ToInt32(rdata, 0);
                    byte[] bodydata=new byte[bodylen];
                    Buffer.BlockCopy(rdata, 4, bodydata, 0, bodylen);

                    int msgid=BitConverter.ToInt32(bodydata, 0);
                    byte[] info=new byte[bodylen-4];
                    Buffer.BlockCopy(bodydata,4,info, 0, info.Length);

                    MsgData msgData = new MsgData();
                    msgData.cli = client;
                    msgData.data = info;
                    MessageManager<MsgData>.Ins.OnBroadCast(msgid, msgData);

                    int sylen = rdata.Length - 4 - bodylen;
                    byte[] sydata=new byte[sylen];
                    Buffer.BlockCopy(rdata,4+bodylen, sydata, 0, sylen);
                    rdata = sydata;
                }

            }
            client.socket.BeginReceive(client.data, 0, client.data.Length, SocketFlags.None, Receive, client);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
    }
    public void OnSendServer(int id, byte[] data,Client client)
    {
        int head = 4 + data.Length;
        byte[] enddata=new byte[0];
        enddata = enddata.Concat(BitConverter.GetBytes(head)).Concat(BitConverter.GetBytes(id)).Concat(data).ToArray();
        client.socket.BeginSend(enddata, 0, enddata.Length, SocketFlags.None, Send, client);
    }

    private void Send(IAsyncResult ar)
    {
        Client client=ar.AsyncState as Client;
        int len = client.socket.EndSend(ar);
        Console.WriteLine("发给客户端消息"+len);
    }
}

客户端

public class NetManager : Singleton<NetManager>
{
    Socket socket;
    byte[] data=new byte[1024];

    Queue<byte[]> queue=new Queue<byte[]>();
    public void InitClient()
    {
        socket=new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        socket.BeginConnect("127.0.0.1", 2201, OnConnect, null);
    }

    private void OnConnect(IAsyncResult ar)
    {
        try
        {
            socket.EndConnect(ar);
            Debug.Log("连接成功");
            socket.BeginReceive(data, 0, data.Length, SocketFlags.None, OnReceive, null);
        }
        catch (Exception ex)
        {
            Debug.Log(ex);
        }
    }

    private void OnReceive(IAsyncResult ar)
    {
        try
        {
            int len =socket.EndReceive(ar);
            if (len > 0)
            {
                byte[] rdata = new byte[len];
                Buffer.BlockCopy(data, 0, rdata, 0, len);
                while (rdata.Length > 4)
                {
                    int bodylen = BitConverter.ToInt32(rdata, 0);
                    byte[] bodydata = new byte[bodylen];
                    Buffer.BlockCopy(rdata, 4, bodydata, 0, bodylen);

                    queue.Enqueue(bodydata);

                    int sylen = rdata.Length - 4 - bodylen;
                    byte[] sydata = new byte[sylen];
                    Buffer.BlockCopy(rdata, 4 + bodylen, sydata, 0, sylen);
                    rdata = sydata;
                }

            }
            socket.BeginReceive(data, 0, data.Length, SocketFlags.None, OnReceive, null);
        }
        catch (Exception ex)
        {
            Debug.Log(ex);
        }
    }
    public void NetUpdata()
    {
        if(queue.Count > 0)
        {
            byte[] bodydata=queue.Dequeue();
            int msgid=BitConverter.ToInt32(bodydata, 0);
            byte[] info=new byte[bodydata.Length-4];
            Buffer.BlockCopy(bodydata, 4, info, 0, info.Length);
            MessageManager<byte[]>.Ins.OnBroadCast(msgid, info);

        }
    }

    public void OnSendClient(int id, byte[] data)
    {
        int head = 4 + data.Length;
        byte[] enddata=new byte[0];
        enddata = enddata.Concat(BitConverter.GetBytes(head)).Concat(BitConverter.GetBytes(id)).Concat(data).ToArray();
        socket.BeginSend(enddata, 0, enddata.Length, SocketFlags.None, OnSend, null);
    }

    private void OnSend(IAsyncResult ar)
    {
        int len = socket.EndSend(ar);
        Debug.Log("发给服务器消息"+len);
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值