Пример #1
0
        /// <summary>
        /// 发送
        /// </summary>
        /// <param name="cs"></param>
        /// <param name="msg"></param>
        public static void Send(ClientState cs, ProtocolBase msg)
        {
            //状态判断
            if (cs == null)
            {
                return;
            }
            if (!cs.socket.Connected)
            {
                return;
            }
            //数据编码
            byte[] nameBytes = ProtocolBase.EncodeName(msg);
            byte[] bodyBytes = ProtocolBase.Encode(msg);
            int    len       = nameBytes.Length + bodyBytes.Length;

            byte[] sendBytes = new byte[2 + len];

            //组装数据长度
            sendBytes[0] = (byte)(len % 256);
            sendBytes[1] = (byte)(len / 256);

            //组装数据名字
            Array.Copy(nameBytes, 0, sendBytes, 2, nameBytes.Length);

            //组装数据消息体
            Array.Copy(bodyBytes, 0, sendBytes, 2 + nameBytes.Length, bodyBytes.Length);
            ByteArray ba = new ByteArray(sendBytes);

            writeQueue.Enqueue(ba);

            try
            {
                cs.socket.BeginSend(sendBytes, 0, sendBytes.Length, 0, null, null);
            }
            catch (SocketException ex)
            {
                Console.WriteLine("Socket Close on BeginSend" + ex.ToString());
            }
        }