Ejemplo n.º 1
0
        public static byte[] StructToBytes(Message obj)
        {
            //得到结构体的大小
            int size = Marshal.SizeOf(obj);

            //创建byte []数组存放数据
            byte[] bytes = new byte[size];
            //Array.Clear(bytes, 0, bytes.Length);

            //分配结构体大小的内存空间
            IntPtr objPtr = Marshal.AllocHGlobal(size);
            try
            {
                //拷贝结构体到分配好的内存空间
                Marshal.StructureToPtr(obj, objPtr, false);
                Marshal.Copy(objPtr, bytes, 0, size);

                //char[] c = Encoding.ASCII.GetChars(bytes);
                //Console.WriteLine("bytes[]={0}", bytes.Length);
                return bytes;
            }
            finally { 
               //释放内存空间
                Marshal.FreeHGlobal(objPtr);
            }
        }
Ejemplo n.º 2
0
        //无法由更高层次的转为低层次的类别,该函数无用
        private void AddToPack(ref Message msg) {
            lock (objLock) {
                package.Enqueue(msg);
            }

        }
Ejemplo n.º 3
0
        //发送协议

        public int Send(Message mproto) {

            if (!msocket.Connected) {
                GameLog.Log(Log.GameLogLevel.FATAL, Log.GameLogType.Conect, "网络断开...");
                Application.Quit();
            }

            byte[] buffer = MTransform.StructToBytes(mproto);
            try {
                //使用异步来send协议
                //msocket.Send(buffer);
                IAsyncResult asySend = msocket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(sendCallback), msocket);
                //超时监控
                bool success = asySend.AsyncWaitHandle.WaitOne(5000, true);
                if (success)
                    GameLog.Log(Log.GameLogLevel.INFO, Log.GameLogType.Conect, mproto.GetType().ToString() + " proto send success!protoID=" + mproto.GetID());
                else
                    GameLog.Log(Log.GameLogLevel.ERROR, Log.GameLogType.Conect, mproto.GetType().ToString() + " proto send timeout! protoID=" + mproto.GetID());
                return 0;
            } catch {
                GameLog.Log(Log.GameLogLevel.ERROR, Log.GameLogType.ProtoLog, mproto.GetType().ToString() + " proto send failed! protoID=" + mproto.GetID());
                return -1;
            }
        }