C#服务器网络框架
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using Google.Protobuf;
namespace ZG5_Server
{
    class NetManager: Singleton<NetManager>
    {
        Socket server;
        public List<Client> clients = new List<Client>();
        public void Init()
        {
            server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ip = new IPEndPoint(IPAddress.Any, 12345);
            server.Bind(ip);
            server.Listen(20);
            Console.WriteLine("服务器开启");
            server.BeginAccept(OnAccept, null);
        }
        private void OnAccept(IAsyncResult ar)
        {
            Socket client = server.EndAccept(ar);
            IPEndPoint iP = client.RemoteEndPoint as IPEndPoint;
            Client cli = new Client();
            cli.socket = client;
            cli.name = iP.Address + ":" + iP.Port;
            clients.Add(cli);
            Console.WriteLine(DateTime.Now.ToString()+ " " + iP.Port + "链接");
            cli.socket.BeginReceive(cli.data, 0, cli.data.Length, SocketFlags.None, OnReceive, cli);
            server.BeginAccept(OnAccept, null);
        }
        private void OnReceive(IAsyncResult ar)
        {
            try
            {
                Client cli = ar.AsyncState as Client;
                int len = cli.socket.EndReceive(ar);
                if (len <= 0)
                {
                    cli.socket.Shutdown(SocketShutdown.Both);
                    cli.socket.Close();
                    clients.Remove(cli);
                    Console.WriteLine(DateTime.Now.ToString() + " " + cli.name + "下线");
                    Leave s2c = new Leave();
                    s2c.PlayerId = cli.player.Id;
                    foreach (var item in clients)
                    {
                        if (item.player != null)
                        {
                            Send(MsgID.S2C_LEAVE, s2c.ToByteArray(), item);
                        }
                    }
                }
                else if (cli.socket.Connected)
                {
                    byte[] data = new byte[len];
                    Buffer.BlockCopy(cli.data, 0, data, 0, data.Length);
                    //创建一个临时流
                    byte[] liu = new byte[cli.stream.Length + data.Length];
                    Buffer.BlockCopy(cli.stream, 0, liu, 0, cli.stream.Length);
                    Buffer.BlockCopy(data, 0, liu, cli.stream.Length, data.Length);
                    //把流替换为临时流
                    cli.stream = liu;
                    //流长度大于等于2说明流内有数据
                    while (cli.stream.Length >= 2)
                    {
                        //获取一个包的长度
                        ushort onelen = BitConverter.ToUInt16(cli.stream, 0);
                        //如果流的长度大于等于包的长度+2说明有一个完整包
                        if (cli.stream.Length >= 2 + onelen)
                        {
                            //获取一个完整包
                            byte[] onedata = new byte[onelen];
                            Buffer.BlockCopy(cli.stream, 2, onedata, 0, onedata.Length);
                            //获取包的消息号
                            int id = BitConverter.ToInt32(onedata, 0);
                            //获取包的消息体
                            byte[] body = new byte[onedata.Length - 4];
                            Buffer.BlockCopy(onedata, 4, body, 0, body.Length);
                            //消息分发
                            Console.WriteLine("收到消息:id" + id);
                            MessageCenter.Ins.Send(id, body, cli);
                            //剩余长度
                            int sylen = cli.stream.Length - (2 + onelen);
                            //剩余长度大于0说明还有包
                            if (sylen > 0)
                            {
                                byte[] sydata = new byte[sylen];
                                Buffer.BlockCopy(cli.stream, 2 + onelen, sydata, 0, sylen);
                                cli.stream = sydata;
                            }
                            else
                            {
                                cli.stream = new byte[0];
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                    #region MyRegion
                    //byte[] data = new byte[len];
                    //Buffer.BlockCopy(cli.data, 0, data, 0, len);
                    ////将收到的消息写入流
                    //cli.my.Write(data, 0, data.Length);
                    ////流长度大于等于2说明有内容(2是包长度ushort的长度)
                    //while (cli.my.Length >= 2)
                    //{
                    //    //读取的起始点
                    //    cli.my.Position = 0;
                    //    int oneLen = cli.my.ReadUshort();
                    //    //判断是否有完整包
                    //    if (cli.my.Length >= 2 + oneLen)
                    //    {
                    //        //获取一个包
                    //        byte[] oneData = new byte[oneLen];
                    //        cli.my.Read(oneData, 0, oneData.Length);
                    //        //解析并分发
                    //        int id = BitConverter.ToInt32(oneData, 0);
                    //        byte[] body = new byte[oneLen - 4];
                    //        Buffer.BlockCopy(oneData, 4, body, 0, body.Length);
                    //        MessageCenter.Ins().Broadcast(id, body, cli);
                    //        int syLen = (int)cli.my.Length - (2 + oneLen);
                    //        //判断流内是否还有剩余内容
                    //        if (syLen > 0)
                    //        {
                    //            //复制出剩余内容
                    //            byte[] syDate = new byte[syLen];
                    //            cli.my.Read(syDate, 0, syDate.Length);
                    //            //清空流
                    //            cli.my.SetLength(0);
                    //            cli.my.Position = 0;
                    //            //将剩余内容写入流
                    //            cli.my.Write(syDate, 0, syDate.Length);
                    //        }
                    //        else
                    //        {
                    //            //清空流
                    //            cli.my.SetLength(0);
                    //            cli.my.Position = 0;
                    //        }
                    //    }
                    //    else
                    //    {
                    //        cli.my.Position = cli.my.Length;
                    //        break;
                    //    } 
                    #endregion
                    cli.socket.BeginReceive(cli.data, 0, cli.data.Length, SocketFlags.None, OnReceive, cli);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
        public void Send(int id, byte[] body, Client cli)
        {
            byte[] head = BitConverter.GetBytes(id);
            byte[] data = new byte[head.Length + body.Length];
            Buffer.BlockCopy(head, 0, data, 0, head.Length);
            Buffer.BlockCopy(body, 0, data, head.Length, body.Length);
            //手动拼接长度
            byte[] mylen = BitConverter.GetBytes((ushort)data.Length);
            byte[] myData = new byte[mylen.Length + data.Length];
            Buffer.BlockCopy(mylen, 0, myData, 0, mylen.Length);
            Buffer.BlockCopy(data, 0, myData, mylen.Length, data.Length);
            cli.socket.BeginSend(myData, 0, myData.Length, SocketFlags.None, OnSend, cli);
        }
        private void OnSend(IAsyncResult ar)
        {
            Client cli = ar.AsyncState as Client;
            int len = cli.socket.EndSend(ar);
            //Console.WriteLine(len);
        }
    }
}

 
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号