Beispiel #1
0
        public bool ConnectServer(ServerInfo serverInfo)
        {
            Server server = GetServer();

            Socket    sock             = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            NetSocket connectSocketCtx = new NetSocket(this);

            connectSocketCtx.sock = sock;

            connectSocketCtx.SetSocketType(NetSocketType.CONNECT_SERVER_SOCKET);
            serverInfo.socketCtx = connectSocketCtx;
            connectSocketCtx.SetRemoteServerInfo(serverInfo);
            connectSocketCtx.dataTransMode      = serverInfo.dataTransMode;
            socketMap[connectSocketCtx.GetID()] = connectSocketCtx;


            if (connectSocketCtx.sock == null)
            {
                connectSocketCtx.SetSocketState(SocketState.INIT_FAILD);
                SocketError(connectSocketCtx);
                //LOG4CPLUS_ERROR(log.GetInst(), "初始化Socket失败,错误代码:" << _GetLastError());
                return(false);
            }

            connectSocketCtx.UpdataTimeStamp();
            Packet packet = connectSocketCtx.CreatePacket(0);

            // 开始连接服务器
            connectSocketCtx.SetSocketState(SocketState.CONNECTTING_SERVER);
            server.IocpPostConnect(packet);

            return(true);
        }
Beispiel #2
0
        void ProcessMsg(NetSocket socket)
        {
            HeaderType header     = new HeaderType();
            ByteStream recvStream = new ByteStream(socket.GetRecvedPack(), socket.GetRecvedPackOffset(), socket.GetRecvedPackSize());
            int        headlen    = ReadStreamToHeader(header, recvStream, true);

            recvStream.ResetExtrenBuf(recvStream.GetBuf(), recvStream.GetCurtPos(), recvStream.GetNumberOfRichBytes());

            if (!IsSingleFrame(header))
            {
                if (isDecryptData)
                {
                    ByteStream decryptDataStream = new ByteStream();
                    Decrypt(header, recvStream, decryptDataStream);
                    decryptDataStream.SetCurt(0);
                    _ProcessMsg(GetMsgTypeValue(header), socket, header, decryptDataStream);
                }
                else
                {
                    _ProcessMsg(GetMsgTypeValue(header), socket, header, recvStream);
                }
            }
            else
            {
                _ProcessSingleFrame(socket, header, recvStream);
            }
        }
Beispiel #3
0
        void ConnectedServerTask(object data)
        {
            Packet    packet    = (Packet)data;
            NetSocket socketCtx = packet.socketCtx;
            Server    server    = GetServer();

            if (CheckingPacketVaild(packet) == 0)
            {
                return;
            }

            if (socketCtx.sock.Connected == false)
            {
                SocketError(socketCtx);
                return;
            }

            socketCtx.sock.EndConnect(packet.ar);
            socketCtx.SetSocketState(SocketState.CONNECTED_SERVER);
            socketCtx.UpdataTimeStamp();

            int bufSize = socketCtx.dePacketor.GetMaxBufferSize();

            if (packet.packBuf.len != bufSize)
            {
                packet = socketCtx.CreatePacket(bufSize);
            }

            socketCtx.dePacketor.UnPack(SocketEvent.EV_SOCKET_CONNECTED, socketCtx);
            server.IocpPostRecv(packet);
        }
Beispiel #4
0
 private bool SocketConnected(NetSocket socket)
 {
     clientSocketID = socket.GetID();
     clientSocket   = socket;
     SendReqUpgradeProtocol(socket, "", "GamePackProtocol");
     return(true);
 }
Beispiel #5
0
        void _UnPack(SocketEvent ev, NetSocket socket, object param)
        {
            MsgProcesser <HeaderType, MsgType> msgProcesser = (MsgProcesser <HeaderType, MsgType>)param;

            socket.SetMsgProcesser(msgProcesser);
            msgProcesser.UnPack(ev, socket);
        }
Beispiel #6
0
        void _ProcessMsg(MsgType msgType, NetSocket socket, HeaderType header, ByteStream dataStream)
        {
            bool           isContinue = true;
            List <MsgFunc> msgfuncList;

            if (msgFuncMap.ContainsKey(msgType))
            {
                msgfuncList = msgFuncMap[msgType];

                for (int i = 0; i < msgfuncList.Count(); i++)
                {
                    if (isContinue)
                    {
                        isContinue = (msgfuncList[i])(socket, header, dataStream);
                    }
                    else
                    {
                        break;
                    }
                }
            }
            else
            {
                // WARNING("消息(%d)没有对应处理函数!", msgType);
            }
        }
Beispiel #7
0
        void SendReqUpgradeProtocol(NetSocket socket, string host, string protocol)
        {
            // ServerInfo serverInfo = socket.GetRemoteServerInfo();
            //  ServerType toServerType = (ServerType)serverInfo->GetTag();
            // Debug.Log("请求%s(%s:%d)更换通信协议为:%s!", SERVER_CN_NAME(toServerType), serverInfo->GetServerIP(), serverInfo->GetServerPort(), protocol.c_str());

            ByteStream sendStream = new ByteStream();
            HttpHeader header     = new HttpHeader();

            sendStream.isByteAlign = false;

            header.type   = 0;
            header.method = HttpRequestMethod.HTTP_METHOD_GET;
            header.url    = "/chat";
            header.ver    = "HTTP/1.1";

            if (host.Length != 0)
            {
                header.fieldMap["Host"] = host;
            }

            header.fieldMap["Connection"]            = "Upgrade";
            header.fieldMap["Upgrade"]               = protocol;
            header.fieldMap["Sec-WebSocket-Version"] = "13";

            byte[] bytedata  = Encoding.Default.GetBytes(Sec_WebSocket_Key);
            string basevalue = Convert.ToBase64String(bytedata);


            header.fieldMap["Sec-WebSocket-Key"] = basevalue;

            httpMsgProcesser.WriteHttpHeader(sendStream, header, false);
            socket.Send(sendStream);
        }
Beispiel #8
0
        public void ReqLogin(string account, string password)
        {
            clientSocket = server.GetSocket(clientSocketID);
            if (clientSocket == null)
            {
                return;
            }

            ByteStream     sendStream = new ByteStream();
            GamePackHeader header     = new GamePackHeader();

            header.type     = GamePackType.MSG_CLIENT_REQ_LOGIN_ENTER;
            header.dataSize = 0;

            int headerlen = gamepackMsgProcesser.WriteGamePackHeader(sendStream, header);

            byte[] accountArray = Encoding.UTF8.GetBytes(account);
            byte[] pwdArray     = Encoding.UTF8.GetBytes(password);

            sendStream.Write((int)DefValue.DEF_CLIENT_COMMON_LOGIN);
            sendStream.Write(account.Length);
            sendStream.WriteBytes(accountArray, 0, accountArray.Length);
            sendStream.Write(pwdArray.Length);
            sendStream.WriteBytes(pwdArray, 0, pwdArray.Length);
            clientSocket.Send(sendStream, headerlen, 0);
        }
Beispiel #9
0
 public NetBase(NetSocket netSocket)
 {
     this.mNetSocket      = netSocket;
     this.mProtoUtil      = mNetSocket.mProtoUtil;
     this.mNetMsgManager  = netSocket.mNetMsgManager;
     this.mNetSocketParam = netSocket.mNetSocketParam;
 }
Beispiel #10
0
 public NetConnect(NetSocket netSocket)
     : base(netSocket)
 {
     if (mNetSocketParam.ShowTip())
     {
         mConnectGameTimer = new GameTimer(2f, 2, OnConnectTimerHandler, OnConnectTimerComplete);
     }
 }
Beispiel #11
0
        private bool RecvRespUpgradeProtoco(NetSocket socket, HttpHeader header, ByteStream dataStream)
        {
            // DEBUG("接收到远端%s响应请求更换通信协议。", socket.remoteIP);

            if (header.isVaild == false)
            {
                return(true);
            }

            if (header.stateCode != 101)
            {
                return(true);
            }


            if (!header.fieldMap.ContainsKey("Upgrade") ||
                !header.fieldMap.ContainsKey("Connection") ||
                !header.fieldMap.ContainsKey("Sec-WebSocket-Accept") ||
                header.fieldMap["Connection"].CompareTo("Upgrade") != 0)
            {
                // DEBUG("远端%s响应请求更换通信协议不合法。", socket.remoteIP);
                socket.Close();
                return(true);
            }

            //
            string stroIn = header.fieldMap["Sec-WebSocket-Accept"];

            byte[] byteArray = Convert.FromBase64String(stroIn);
            string pOut      = Encoding.Default.GetString(byteArray);


            byte[] bytedata = Encoding.Default.GetBytes(Sec_WebSocket_Key);
            string seckey   = Convert.ToBase64String(bytedata);
            string key      = seckey + Sec_WebSocket_Key_2;


            SHA1 sha1 = new SHA1CryptoServiceProvider();

            byte[] bytes_in  = Encoding.Default.GetBytes(key);
            byte[] bytes_out = sha1.ComputeHash(bytes_in);
            string chSha1    = Encoding.Default.GetString(bytes_out);

            if (chSha1.CompareTo(pOut) != 0)
            {
                //DEBUG("远端%s响应请求更换通信协议不合法。", socket.remoteIP);
                socket.Close();
                return(true);
            }

            if (header.fieldMap["Upgrade"].CompareTo("GamePackProtocol") == 0)
            {
                socket.SetDePacketor(gamepackDePacketor);
                socket.SetMsgProcesser(gamepackMsgProcesser);
            }

            return(true);
        }
Beispiel #12
0
 public void SetCurtPack(NetSocket socket, byte[] _curtPack, int _curtPackLen)
 {
     curtDepacketSocket = socket;
     curtPack           = _curtPack;
     curtPackLen        = _curtPackLen;
     cachePack          = curtDepacketSocket.cachePack;
     cachePackLen       = curtDepacketSocket.cachePackLen;
     cachePackOffset    = curtDepacketSocket.cachePackOffset;
 }
Beispiel #13
0
        public NetSocket GetSocket(ulong socketID)
        {
            if (!socketMap.ContainsKey(socketID))
            {
                return(null);
            }

            NetSocket socket = socketMap[socketID];

            return(socket);
        }
Beispiel #14
0
        int SocketError(ulong socketID)
        {
            NetSocket socket = GetSocket(socketID);

            if (socket == null)
            {
                return(0);
            }
            SocketError(socket);
            return(0);
        }
Beispiel #15
0
        void ErrorTask(object data)
        {
            Packet    packet    = (Packet)data;
            NetSocket socketCtx = packet.socketCtx;
            Server    server    = GetServer();

            if (CheckingPacketVaild(packet) == 0)
            {
                return;
            }

            SocketError(socketCtx);
        }
Beispiel #16
0
        void SingleIocpAcceptTask(object data)
        {
            Packet    packet    = (Packet)data;
            Server    server    = GetServer();
            NetSocket socketCtx = null;

            // 投递新的AcceptEx
            socketCtx = new NetSocket(this);
            socketCtx.SetSocketType(NetSocketType.LISTEN_CLIENT_SOCKET);
            packet.socketCtx = socketCtx;

            server.IocpPostAccept(packet);
        }
Beispiel #17
0
        public void UnPack(SocketEvent ev, NetSocket socket)
        {
            BaseMsgProcesser msgProcesser = socket.GetMsgProcesser();

            if (msgProcesser != null)
            {
                msgProcesser.UnPack(ev, socket);
            }
            else if (unPack != null)
            {
                unPack(ev, socket);
                socket.SetMsgProcesser((BaseMsgProcesser)unPackParam);
            }
        }
Beispiel #18
0
        public Packet(NetSocket _socketCtx, int _maxBufSize = 1024)
        {
            socketCtx  = _socketCtx;
            serverTask = socketCtx.serverTask;
            socketID   = socketCtx.GetID();
            maxBufSize = _maxBufSize;

            if (_maxBufSize != 0)
            {
                buf = new byte[maxBufSize];
                Array.Clear(buf, 0, buf.Length);
            }

            packBuf.buf = buf;
            packBuf.len = maxBufSize;
        }
Beispiel #19
0
        void StartInitIocpAcceptTask(object data)
        {
            Server    server = GetServer();
            Packet    packet;
            NetSocket newSocketCtx;

            // 为AcceptEx 准备参数,然后投递AcceptEx I/O请求
            for (int i = 0; i < 20; i++)
            {
                newSocketCtx = new NetSocket(this);
                newSocketCtx.SetSocketType(NetSocketType.LISTEN_CLIENT_SOCKET);

                packet = newSocketCtx.CreatePacket(0);
                server.IocpPostAccept(packet);
            }
        }
Beispiel #20
0
        //此任务根据设置可能在其它任务处理线上执行
        void SendedTask(object data)
        {
            Packet    packet    = (Packet)data;
            NetSocket socketCtx = packet.socketCtx;
            Server    server    = GetServer();

            if (CheckingPacketVaild(packet) == 0)
            {
                return;
            }

            SocketError socketError = System.Net.Sockets.SocketError.Success;

            packet.transferedBytes = socketCtx.sock.EndSend(packet.ar, out socketError);
            if (socketError != System.Net.Sockets.SocketError.Success)
            {
                SocketError(socketCtx);
                return;
            }


            if (useSendedEvent)
            {
                if (useSingleSendDataTaskProcesser)
                {
                    PostTask(ProcessSendedMsgTask, packet.socketID);
                }
                else
                {
                    socketCtx.dePacketor.UnPack(SocketEvent.EV_SOCKET_SEND, socketCtx);
                }
            }


            List <Packet> sendList = socketCtx.sendList;

            if (sendList.Count == 0)
            {
                return;
            }

            packet = sendList[0];
            sendList.RemoveAt(0);
            server.IocpPostSend(packet);
        }
Beispiel #21
0
 int SocketError(NetSocket socket)
 {
     if (useSingleSendDataTaskProcesser)
     {
         sendTaskProcesser.PostTask(PasueSendTask, null, this, TaskMsg.TMSG_PAUSE);
         socket.dePacketor.UnPack(SocketEvent.EV_SOCKET_OFFLINE, socket);
         socketErrorWaitSem.WaitOne();
         socketErrorWaitSem.Reset();
         RemoveSocket(socket.GetID());
         sendTaskProcesser.Continue();
     }
     else
     {
         socket.dePacketor.UnPack(SocketEvent.EV_SOCKET_OFFLINE, socket);
         RemoveSocket(socket.GetID());
     }
     return(0);
 }
Beispiel #22
0
        void RecvedTask(object data)
        {
            Packet    packet    = (Packet)data;
            NetSocket socketCtx = packet.socketCtx;
            Server    server    = GetServer();

            if (CheckingPacketVaild(packet) == 0)
            {
                return;
            }

            SocketError socketError = System.Net.Sockets.SocketError.Success;

            packet.transferedBytes = socketCtx.sock.EndReceive(packet.ar, out socketError);

            if (socketError != System.Net.Sockets.SocketError.Success)
            {
                SocketError(socketCtx);
                return;
            }

            socketCtx.UpdataTimeStamp();

            if (socketCtx.dataTransMode == DataTransMode.MODE_PACK)
            {
                socketCtx.dePacketor.SetCurtPack(socketCtx, packet.buf, packet.transferedBytes);
                int ret = socketCtx.dePacketor.Extract();

                if (ret == 2)
                {
                    socketCtx.SetSocketState(SocketState.RECV_DATA_TOO_BIG);
                    SocketError(socketCtx.GetID());
                }
            }
            else
            {
                socketCtx.SetPack(packet.buf, 0, packet.transferedBytes);
                socketCtx.dePacketor.UnPack(SocketEvent.EV_SOCKET_RECV, socketCtx);
                socketCtx.RemovePack();
            }

            // 然后开始投递下一个WSARecv请求
            server.IocpPostRecv(packet);
        }
Beispiel #23
0
        void OnAcceptCallBack(IAsyncResult ar)
        {
            Packet    packet       = ar.AsyncState as Packet;
            NetSocket newSocketCtx = packet.socketCtx;

            //接收结果
            newSocketCtx.sock = listenSocket.sock.EndAccept(ar);

            newSocketCtx.SetSocketState(SocketState.CONNECTED_CLIENT);
            newSocketCtx.UpdataTimeStamp();

            Packet newPacket = newSocketCtx.CreatePacket(dePacketor.GetMaxBufferSize());

            serverTaskMgr.PostServerMessage(ServerMessage.SMSG_ACCEPT_CLIENT, newPacket);


            //继续接受客户端的请求
            serverTaskMgr.PostSingleIocpAccpetTask(packet);
        }
Beispiel #24
0
        bool CreateListener()
        {
            Server    server    = GetServer();
            NetSocket listenCtx = null;

            // 生成用于监听的Socket的信息
            if (listenCtx == null)
            {
                Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                listenCtx      = new NetSocket(this);
                listenCtx.sock = sock;
            }

            listenCtx.SetSocketType(NetSocketType.LISTENER_SOCKET);

            if (null == listenCtx.sock)
            {
                listenCtx.SetSocketState(SocketState.INIT_FAILD);
                SocketError(listenCtx);
                //LOG4CPLUS_ERROR(log.GetInst(), "初始化Socket失败,错误代码:"<<_GetLastError());
                return(false);
            }

            SetListenerContext(listenCtx);
            socketMap[listenCtx.GetID()] = listenCtx;

            //实例一个网络端点  传入地址和端口
            IPEndPoint serverEP = new IPEndPoint(IPAddress.Any, 23456);

            //绑定网络端点
            listenCtx.sock.Bind(serverEP);
            //设置最大监听数量
            listenCtx.sock.Listen(0x7fffffff);

            listenCtx.SetSocketState(SocketState.LISTENING);

            serverTaskMgr.PostServerMessage(ServerMessage.SMSG_LISTENER_CREATE_FINISH, null);

            return(true);
        }
Beispiel #25
0
        void ProcessSocketEvent(SocketEvent ev, NetSocket socket)
        {
            List <SocketEventFunc> socketEvFuncList;

            if (socketEventFuncMap.ContainsKey(ev))
            {
                socketEvFuncList = socketEventFuncMap[ev];

                bool isContinue = true;
                for (int i = 0; i < socketEvFuncList.Count; i++)
                {
                    if (isContinue)
                    {
                        (socketEvFuncList[i])(socket);
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }
Beispiel #26
0
        public override void UnPack(SocketEvent ev, NetSocket socket)
        {
            switch (ev)
            {
            case SocketEvent.EV_SOCKET_RECV:
            {
                if (socket.dataTransMode == DataTransMode.MODE_PACK)
                {
                    ProcessMsg(socket);
                }
                else
                {
                    ProcessSocketEvent(ev, socket);
                }
            }
            break;

            default:
                ProcessSocketEvent(ev, socket);
                break;
            }
        }
Beispiel #27
0
        void AcceptedClientTask(object data)
        {
            Packet    packet    = (Packet)data;
            NetSocket socketCtx = packet.socketCtx;
            Server    server    = GetServer();

            // 把这个有效的客户端信息,加入到socketMap中去
            socketMap[socketCtx.GetID()] = socketCtx;

            socketCtx.SetPack(packet.buf, 0, packet.transferedBytes);
            socketCtx.dePacketor.UnPack(SocketEvent.EV_SOCKET_ACCEPTED, socketCtx);
            socketCtx.RemovePack();

            int bufSize = socketCtx.dePacketor.GetMaxBufferSize();

            if (packet.packBuf.len != bufSize)
            {
                packet = socketCtx.CreatePacket(bufSize);
            }

            server.IocpPostRecv(packet);
        }
Beispiel #28
0
        //此任务根据设置可能在其它任务处理线上执行
        void SendTask(object data)
        {
            Packet    packet    = (Packet)data;
            NetSocket socketCtx = packet.socketCtx;
            Server    server    = GetServer();

            if (CheckingPacketVaild(packet) == 0)
            {
                return;
            }

            List <Packet> sendList = socketCtx.sendList;

            if (sendList.Count == 0)
            {
                server.IocpPostSend(packet);
            }
            else
            {
                sendList.Add(packet);
            }
        }
Beispiel #29
0
        void _ProcessSingleFrame(NetSocket socket, HeaderType singleFrameHeader, ByteStream singleFrameDataStream)
        {
            if (socket.joinFrameDataStream == null)
            {
                socket.joinFrameDataStream             = new ByteStream();
                socket.joinFrameDataStream.isByteAlign = false;
                socket.joinFrameHeader = singleFrameHeader;
                socket.joinFrameDataStream.WriteBytes(singleFrameDataStream.GetBuf(), singleFrameDataStream.GetCurtOffset(), singleFrameDataStream.GetNumberOfWriteBytes());
                return;
            }

            bool isFinish = ProcessSingleDataFrame(
                (HeaderType)socket.joinFrameHeader, socket.joinFrameDataStream,
                singleFrameHeader, singleFrameDataStream);

            if (isFinish)
            {
                HeaderType header = (HeaderType)socket.joinFrameHeader;
                socket.joinFrameDataStream.SetCurt(0);

                if (isDecryptData)
                {
                    ByteStream decryptDataStream = new ByteStream();
                    Decrypt(header, socket.joinFrameDataStream, decryptDataStream);
                    decryptDataStream.SetCurt(0);
                    _ProcessMsg(GetMsgTypeValue(header), socket, header, decryptDataStream);
                }
                else
                {
                    _ProcessMsg(GetMsgTypeValue(header), socket, header, socket.joinFrameDataStream);
                }

                socket.joinFrameHeader     = null;
                socket.joinFrameDataStream = null;
            }
        }
Beispiel #30
0
 public NetSend(NetSocket netSocket)
     : base(netSocket)
 {
 }