Close() 공개 메소드

public Close ( ) : void
리턴 void
예제 #1
0
    /// <summary>
    /// 发送消息给server
    /// </summary>
    /// <param name="datas"></param>
    public void SendMessage(int msgId, byte[] datas)
    {
        ByteBuffer writeBuffer = null;

        try
        {
            if (this.socket == null)
            {
                return;
            }

            writeBuffer = new ByteBuffer();

            writeBuffer.WriteInt(msgId);
            writeBuffer.WriteInt(datas.Length);
            writeBuffer.WriteBytes(datas);
            var sendBytes = writeBuffer.ToBytes();
            DebugLog(identiy, "send msg id : " + msgId + "  len: " + datas.Length);
            writeBuffer.Close();

            socket.BeginSend(sendBytes, 0, sendBytes.Length, SocketFlags.None, new AsyncCallback(this.SendMessageCallBack), socket);
        }
        catch (Exception e)
        {
            if (writeBuffer != null)
            {
                writeBuffer.Close();
            }

            DoSocketException();

            DebugLogError(identiy, e.ToString());
        }
    }
예제 #2
0
    /// <summary>
    /// 接收到消息
    /// startIndex:0 length:4
    /// MessageType startIndex:4 length:2
    /// ProtocalType startIndex:6 length:2
    /// BodyLength startIndex:8 length:4
    /// </summary>
    /// <param name="ms"></param>
    void OnReceivedMessage(MemoryStream ms, short protocal, short messageID, int bufLength)
    {
        BinaryReader r = new BinaryReader(ms);

        //if (protocal != Protocal.Heartbeat)
        //{
        //    Util.OtherLog("解析大厅消息,编号==================" + protocal);
        //}
        //移除超时
        Main.NetworkManager.RemoveTimeOut(socketType, messageID);

        byte[] oldBytes = r.ReadBytes((int)(ms.Length - ms.Position));
        byte[] newBytes = new byte[1024];
        //if (clientType == ClientType.Hall)
        //    newBytes = SecurityManager.Decrypt(protocal, oldBytes, AppConst.desHallKey);
        //else
        //    newBytes = SecurityManager.Decrypt(protocal, oldBytes, AppConst.desBt7Key);

        ByteBuffer buffer = new ByteBuffer();

        buffer.WriteBytes(oldBytes);
        ByteBuffer _buffer = new ByteBuffer(buffer.ToBytes());

        buffer.Close();
        Main.NetworkManager.AddEvent(socketType, protocal, _buffer);
    }
예제 #3
0
파일: SocketClient.cs 프로젝트: mengtest/wh
    /// <summary>
    /// 发送消息
    /// </summary>
    public void SendMessage(ByteBuffer buffer)
    {
        try
        {
            if (!isConnect)
            {
                Close();
                return;
            }

            //byte[] data=buffer.ToBytes();

            //foreach (byte b in data)
            //{
            //    Debug.Log("=============================================================");
            //    Debug.Log(b);  //法1
            //}

            WriteMessage(buffer.ToBytes());
            buffer.Close();
        }
        catch (Exception e)
        {
            Debug.Log(e.Message);
            AddExceptionMsg("Connect failed! SendMessage");
        }
    }
예제 #4
0
    private void UnPackProtocol(byte[] msg_bytes)
    {
        ByteBuffer buffer = new ByteBuffer(Encrypt.Decode(msg_bytes, Encrypt.DefaultKey));

        //读出附加位
        int addition = buffer.ReadInt();

        //读出用户ID列表
        int list_lenght = buffer.ReadInt();

        //读出协议体
        byte[]   protocol_bytes = buffer.ReadBytes((int)buffer.RemainingBytes());
        IMessage protocol       = Protocol.Decode(protocol_bytes);

        buffer.Close();

        if (protocol != null)
        {
            Debug.Log("客户端接收消息:" + protocol.GetType() + " 数据:" + protocol.ToString());
            lock (msg_lock)
            {
                this.protocol_list.Add(protocol);
            }
        }
    }
예제 #5
0
    private byte[] PackProtocol(IMessage protocol, int addition = 0, List <int> player_id_list = null)
    {
        ByteBuffer buffer = new ByteBuffer();

        //写入附加位
        buffer.WriteInt(addition);

        //写入玩家ID列表
        if (player_id_list != null)
        {
            buffer.WriteInt(player_id_list.Count);
            foreach (int user_id in player_id_list)
            {
                buffer.WriteInt(user_id);
            }
        }
        else
        {
            buffer.WriteInt(0);
        }

        //写入协议体
        byte[] protocol_bytes = Protocol.Encode(protocol);
        buffer.WriteBytes(protocol_bytes);

        byte[] msg_bytes = buffer.ToBytes();
        buffer.Clear();
        buffer.WriteInt(msg_bytes.Length);
        buffer.WriteBytes(Encrypt.Encode(msg_bytes, Encrypt.DefaultKey));
        msg_bytes = buffer.ToBytes();
        buffer.Close();

        return(msg_bytes);
    }
예제 #6
0
    public void SendMessage(short protocal, short messageID, byte[] buf, string key)
    {
        //if (protocal != Protocal.Heartbeat)
        //{
        //    Util.Log("发送大厅消息,编号=========== " + protocal);
        //}
        // 加密
        ByteBuffer buffer = new ByteBuffer();

        buffer.WriteShort(protocal);
        buffer.WriteShort(messageID);
        if (buf != null)
        {
            //buffer.WriteBytes(SecurityManager.Encrypt(protocal, buf, key));   //加密
            buffer.WriteBytes(buf);
        }
        else
        {
            buffer.WriteInt(0);
        }

        byte[] bytes = buffer.ToBytes();
        WriteMessage(bytes, messageID, protocal);
        buffer.Close();
    }
예제 #7
0
    static int Close(IntPtr L)
    {
        LuaScriptMgr.CheckArgsCount(L, 1);
        ByteBuffer obj = (ByteBuffer)LuaScriptMgr.GetNetObjectSelf(L, 1, "ByteBuffer");

        obj.Close();
        return(0);
    }
예제 #8
0
    static int Close(IntPtr L)
    {
        LuaScriptMgr.CheckArgsCount(L, 1);
        ByteBuffer obj = LuaScriptMgr.GetNetObject <ByteBuffer>(L, 1);

        obj.Close();
        return(0);
    }
예제 #9
0
    public void SendMessageSync(MSG_CS msgId, IMessage request)
    {
        requestStream.SetLength(0);
        MessageExtensions.WriteTo(request, requestStream);
        ByteBuffer buffer = createByteBuffer((ushort)msgId, requestStream);

        client.WriteMessage(buffer.ToBytes());
        buffer.Close();
    }
예제 #10
0
    /// <summary>
    /// 丢失链接
    /// </summary>
    void OnDisconnected(Protocal protocal, short error, string msg)
    {
        Close();
        ByteBuffer buffer = new ByteBuffer();

        buffer.WriteShort(error);
        buffer.WriteString(msg);
        NetworkManager.AddEvent((int)protocal, new ByteBuffer(buffer.ToBytes()));
        buffer.Close();
    }
예제 #11
0
    public static void SendConnect(string addr, int port)
    {
        ioo.gameManager.GetComponent <SocketClient>()._errorMsg = "";
        ByteBuffer buffer = new ByteBuffer();

        buffer.WriteString(addr);
        buffer.WriteInt(port);
        _events.Enqueue(new KeyValuePair <NetActionType, ByteBuffer>(NetActionType.Connect, new ByteBuffer(buffer.ToBytes())));
        buffer.Close();
    }
        /// <summary>
        /// 发送消息
        /// </summary>
        public void SendMessage(ByteBuffer buffer)
        {
            if (!IsConnected())
            {
                return;
            }

            SessionSend(buffer.ToBytes());
            buffer.Close();
        }
예제 #13
0
    /// <summary>
    /// 交给Command,这里不想关心发给谁。
    /// </summary>
    void Update()
    {
        if (sEvents.Count > 0)
        {
            lock (sEvents)
            {
                while (sEvents.Count > 0)
                {
                    ServerEvent _event = sEvents.Dequeue();
                    if (_event == null)
                    {
                        Util.LogError("ServerType is null");
                        continue;
                    }
                    Distribute(_event._type, _event.Key, _event.Value);
                }
            }
        }
        lock (timeOutList)
        {
            if (timeOutList.Count > 0)
            {
                float curTime = Time.unscaledTime;

                for (int i = timeOutList.Count - 1; i >= 0; i--)
                {
                    if (isStopUpdate)
                    {
                        isStopUpdate = false;
                        break;
                    }
                    MessageTimeOut mto = timeOutList[i];
                    if (curTime - mto.beginTime >= AppConst.SendMessageTimeOut)
                    {     //超时了
                        if (IsHandleTimeOut(mto.protocal))
                        { //超时处理
                            Util.LogError("server->" + mto.server + "--protocal-->" + mto.protocal + "--messageID-->" + mto.messageID + "--timeout");

                            ByteBuffer buffer = new ByteBuffer();
                            buffer.WriteShort((short)mto.server);
                            buffer.WriteShort(mto.protocal);

                            ByteBuffer _buffer = new ByteBuffer(buffer.ToBytes());
                            buffer.Close();
                            AddEvent(ServerType.Logic, ClientProtocal.TimeOut, _buffer);
                            //EventManager.instance.NotifyEvent(NetEventType.TimeOut, mto.protocal);
                        }
                        timeOutList.Remove(mto);
                    }
                }
            }
        }
    }
예제 #14
0
    // 发送验证消息
    public static void SendVerifyMessage(int type)
    {
        ByteBuffer buff = new ByteBuffer();

        buff.WriteInt(GameConst.MSG_VERIFY_ID);
        buff.WriteInt(4);
        buff.WriteInt(type);

        byte[] bytes = buff.ToBytes();
        buff.Close();

        GameSocket.Instance.SendMessageNoCallBack(bytes);
    }
예제 #15
0
        /// <summary>
        /// pbc消息
        /// </summary>
        void OnPbcMessage(ClientSession session, ByteBuffer buffer) {
            tutorial.Person request = ProtoUtil.GetMessage<tutorial.Person>(buffer);
            Console.WriteLine("OnPbcMessage id=>>" + request.id + " name:>>>" + request.name);
            buffer.Close(); buffer = null;

            byte[] data = ProtoUtil.SetMessage<tutorial.Person>(request);

            ByteBuffer newBuffer = new ByteBuffer();
            newBuffer.WriteByte((byte)ProtocalType.PBC);
            newBuffer.WriteBytes(data); //添加数据

            SocketUtil.SendMessage(session, Protocal.Login, newBuffer);
        }
예제 #16
0
 /// <summary>
 /// Connection is locked before this method is called.
 /// </summary>
 protected override void CloseConnection()
 {
     // dispose of all resources
     if (_byteStream != null)
     {
         _byteStream.Close();
     }
     if (_fileStream != null)
     {
         _fileStream.Close();
     }
     _byteStream = null;
     _fileStream = null;
 }
예제 #17
0
 static int Close(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 1);
         ByteBuffer obj = (ByteBuffer)ToLua.CheckObject(L, 1, typeof(ByteBuffer));
         obj.Close();
         return(0);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
예제 #18
0
 void onReceive(object sender, byte[] data)
 {
     if (null != NetMgr)
     {
         ByteBuffer buffer = new ByteBuffer();
         buffer.WriteBytes(data);
         NetMgr.AddEvent(Protocal.GameData, new ByteBuffer(buffer.ToBytes()));
         buffer.Close();
     }
     else
     {
         LogUtil.Log("onReceive:{0}", GameUtil.ToHexString(data));
     }
 }
예제 #19
0
        /// <summary>
        /// pblua消息
        /// </summary>
        /// <param name="session"></param>
        /// <param name="buffer"></param>
        void OnPbLuaMessage(ClientSession session, ByteBuffer buffer) {
            LoginRequest request = ProtoUtil.GetMessage<LoginRequest>(buffer);
            Console.WriteLine("OnPbLuaMessage id=>>" + request.id + " name:>>>" + request.name + " email:>>" + request.email);
            buffer.Close(); buffer = null;

            LoginResponse response = new LoginResponse();
            response.id = 100; //排队人数
            byte[] data = ProtoUtil.SetMessage<LoginResponse>(response);

            ByteBuffer newBuffer = new ByteBuffer();
            newBuffer.WriteByte((byte)ProtocalType.PB_LUA);
            newBuffer.WriteBytes(data); //添加数据

            SocketUtil.SendMessage(session, Protocal.Login, newBuffer);
        }
예제 #20
0
        /// <summary>
        /// pbc消息
        /// </summary>
        void OnPbcMessage(ClientSession session, ByteBuffer buffer)
        {
            tutorial.Person request = ProtoUtil.GetMessage <tutorial.Person>(buffer);
            Console.WriteLine("OnPbcMessage id=>>" + request.id + " name:>>>" + request.name);
            buffer.Close(); buffer = null;

            byte[] data = ProtoUtil.SetMessage <tutorial.Person>(request);

            ByteBuffer newBuffer = new ByteBuffer();

            newBuffer.WriteByte((byte)ProtocalType.PBC);
            newBuffer.WriteBytes(data); //添加数据

            SocketUtil.SendMessage(session, Protocal.Login, newBuffer);
        }
예제 #21
0
    // 向服务器发送队列里的消息
    public void handleSend()
    {
        if (!IsConnect)
        {
            return;
        }

        while (sendQueue.Count > 0)
        {
            ByteBuffer buffer = sendQueue.Dequeue();
            dispatchEvent(NET_EVENT.SEND_START, buffer.getMsgId());
            client.WriteMessage(buffer.ToBytes());
            buffer.Close();
        }
    }
예제 #22
0
        //----------------------------------//

        /// <summary>
        /// Process the completed message. This can involve decryption and decompression.
        /// </summary>
        private void PostprocessBody()
        {
            // move to the start of the stream
            _streamBuffer.Position = 0;

            // is the message encrypted?
            if (Header.EncryptionPassword != null)
            {
                // yes, decrypt using the password
                var stream = Crypto.DecryptWithPassword(_streamBuffer.Stream, Header.EncryptionPassword);

                // if stream is null, the data wasn't able to be decrypted - throw
                if (stream == null)
                {
                    throw new InvalidDataException("Stream was unable to be decrypted.");
                }

                // dispose of the encrypted stream
                _streamBuffer.Stream.Dispose();

                // create a new buffer from the decrypted stream
                _streamBuffer.Stream = stream;

                // reset buffer position
                _streamBuffer.Position = 0;

                // set the adjusted body length
                Header.BodyLength = (int)_streamBuffer.WriteEnd;
            }

            // is the message compressed?
            if (Header.Compression != System.Net.DecompressionMethods.None)
            {
                // yes, decompress the message
                var stream = StreamHelper.Decompress(Header.Compression, _streamBuffer.Stream, ref Header.BodyLength);
                // dispose of the compressed stream
                _streamBuffer.Close();

                // create a new buffer from the decompressed stream
                _streamBuffer.Stream = stream;

                // reset buffer position
                _streamBuffer.Position = 0;

                // set the adjusted body length
                Header.BodyLength = (int)_streamBuffer.WriteEnd;
            }
        }
예제 #23
0
    private void UnPackProtocol(byte[] msg_bytes, int connect_id)
    {
        ByteBuffer buffer = new ByteBuffer(msg_bytes);

        //读出协议体
        byte[]   protocol_bytes = buffer.ReadBytes((int)buffer.RemainingBytes());
        IMessage protocol       = Protocol.Decode(protocol_bytes);

        buffer.Close();

        if (protocol != null)
        {
            Log.Debug("服务端接收消息:" + protocol.GetType() + " 数据:" + protocol.ToString());
            this.DispatchProtocol(protocol, connect_id);
        }
    }
예제 #24
0
    private static int Close(IntPtr L)
    {
        int result;

        try
        {
            ToLua.CheckArgsCount(L, 1);
            ByteBuffer byteBuffer = (ByteBuffer)ToLua.CheckObject(L, 1, typeof(ByteBuffer));
            byteBuffer.Close();
            result = 0;
        }
        catch (Exception e)
        {
            result = LuaDLL.toluaL_exception(L, e, null);
        }
        return(result);
    }
예제 #25
0
    //public void SocketSend(string sendStr)
    //{
    //    //清空发送缓存
    //    byte[] sendData = new byte[1024];
    //    //数据类型转换
    //    sendData = Encoding.ASCII.GetBytes(sendStr);
    //    //发送
    //    serverSocket.Send(sendData, sendData.Length, SocketFlags.None);
    //}

    /// <summary>
    /// 写数据
    /// </summary>
    public void WriteMessage(byte[] message)
    {
        if (serverSocket != null && serverSocket.Connected)
        {
            ByteBuffer byteBuffer = new ByteBuffer();
            byteBuffer.WriteUInt16((ushort)message.Length);
            byteBuffer.WriteBytes(message);
            byte[] payload = byteBuffer.ToBytes();
            byteBuffer.Close();
            //PrintBytes (payload);
            serverSocket.Send(payload, payload.Length, SocketFlags.None);
        }
        else
        {
            Debug.LogError("client.connected----->>false");
        }
    }
예제 #26
0
    private void SendHeartMessage()
    {
        if (sockets.Count <= 0)
        {
            return;
        }

        ByteBuffer buff = new ByteBuffer();

        buff.WriteInt(MSG_HEART_ID);
        buff.WriteInt(0);

        byte[] bytes = buff.ToBytes();
        buff.Close();

        SendMessages(bytes);
    }
예제 #27
0
 /// <summary>
 /// 写数据
 /// </summary>
 public void WriteMessage(byte[] message)
 {
     if (client != null && client.Connected)
     {
         ByteBuffer byteBuffer = new ByteBuffer();
         byteBuffer.WriteUInt16((ushort)message.Length);
         byteBuffer.WriteBytes(message);
         byte[] payload = byteBuffer.ToBytes();
         byteBuffer.Close();
         //PrintBytes (payload);
         outStream.BeginWrite(payload, 0, payload.Length, new AsyncCallback(OnWrite), null);
     }
     else
     {
         Debug.LogError("client.connected----->>false");
     }
 }
예제 #28
0
    private byte[] PackProtocol(IMessage protocol)
    {
        ByteBuffer buffer = new ByteBuffer();

        //写入协议体
        byte[] protocol_bytes = Protocol.Encode(protocol);
        buffer.WriteBytes(protocol_bytes);

        byte[] msg_bytes = buffer.ToBytes();
        buffer.Clear();
        buffer.WriteInt(msg_bytes.Length);
        buffer.WriteBytes(msg_bytes);
        msg_bytes = buffer.ToBytes();
        buffer.Close();

        return(msg_bytes);
    }
예제 #29
0
        /// <summary>
        /// 判断是否为Dicom文件
        /// </summary>
        /// <returns></returns>
        private bool IsDicom()
        {
            try
            {
                _buffer.Seek(128L, SeekOrigin.Begin);
                if (_buffer.ReadBytesToString(4) != "DICM")
                {
                    Console.WriteLine(@"没有DICM前缀,文件格式错误!");
                    return(false);
                }

                return(true);
            }
            catch (Exception)
            {
                _buffer.Close();
                return(false);
            }
        }
예제 #30
0
        public Version(byte[] bs)
        {
            var buffer = new ByteBuffer(bs);

            version = buffer.ReadString();
            var count = buffer.ReadInt();

            AllAB = new List <ABInfo>();
            for (int i = 0; i < count; i++)
            {
                ABInfo info = new ABInfo();
                info.name = buffer.ReadString();
                info.sha1 = buffer.ReadString();
                info.size = buffer.ReadLong();
                AllAB.Add(info);
            }
            buffer.Close();
        }
예제 #31
0
        public byte[] ToBytes()
        {
            var buffer = new ByteBuffer();

            buffer.WriteString(version);
            buffer.WriteInt(AllAB.Count);
            foreach (var abInfo in AllAB)
            {
                buffer.WriteString(abInfo.name);
                buffer.WriteString(abInfo.sha1);
                buffer.WriteLong(abInfo.size);
            }

            var bt = buffer.ToBytes();

            buffer.Close();
            return(bt);
        }
예제 #32
0
        /// <summary>
        /// pblua消息
        /// </summary>
        /// <param name="session"></param>
        /// <param name="buffer"></param>
        void OnPbLuaMessage(ClientSession session, ByteBuffer buffer)
        {
            LoginRequest request = ProtoUtil.GetMessage <LoginRequest>(buffer);

            Console.WriteLine("OnPbLuaMessage id=>>" + request.id + " name:>>>" + request.name + " email:>>" + request.email);
            buffer.Close(); buffer = null;

            LoginResponse response = new LoginResponse();

            response.id = 100; //排队人数
            byte[] data = ProtoUtil.SetMessage <LoginResponse>(response);

            ByteBuffer newBuffer = new ByteBuffer();

            newBuffer.WriteByte((byte)ProtocalType.PB_LUA);
            newBuffer.WriteBytes(data); //添加数据

            SocketUtil.SendMessage(session, Protocal.Login, newBuffer);
        }
예제 #33
0
 public void ConnectToServer(string host,int port,ByteBuffer login_msg)
 {
     SocketClient.ConnectToServer(host, port, login_msg.ToBytes());
     login_msg.Close();
 }
예제 #34
0
 /// <summary>
 /// 发送消息
 /// </summary>
 public void SendMessage(ByteBuffer buffer)
 {
     SessionSend(buffer.ToBytes());
     buffer.Close();
 }
예제 #35
0
        /// <summary>
        /// sproto消息
        /// </summary>
        void OnSprotoMessage(ClientSession session, ByteBuffer buffer) {
            byte[] data = buffer.ReadBytes();
            //-------------------------------------------------------------
            SprotoPack spack = new SprotoPack();
            byte[] pack_data = spack.pack(data);             // pack
            byte[] unpack_data = spack.unpack(pack_data);     // unpack

            AddressBook addr = new AddressBook(unpack_data);   // decode
            Console.WriteLine("OnSprotoMessage id=>>" + addr.person.Count);
            buffer.Close(); buffer = null;

            //-------------------------------------------------------------
            ByteBuffer newBuffer = new ByteBuffer();
            newBuffer.WriteByte((byte)ProtocalType.SPROTO);
            newBuffer.WriteBytes(data); //添加数据
            SocketUtil.SendMessage(session, Protocal.Login, newBuffer);
        }