基于kjavaQQ1.4版本协议的整理与重写

  这好像还是今年年初弄的一个东西,当时忘了是为了什么了,反正就是弄了这个手机QQ的协议,然后自己根据这开始写了一个简陋的QQ客户端,越来越有种想法,感觉该去看看C++了,对于C#这一年粗略的研究了很多东西,总结开来--码,不想继续这种想法,在整理完以前的东西之后,就去大踏步的开进C++

  这个是手机QQ,基于1.4版本的协议,经测试一切正常,能够实现的功能在代码里都有注释,还有webQQ和飞信,有想研究的可以自行去研究,感觉那两个虽然有实现,但不是想这个这样自己去拦截封包然后测试,在能发消息的那一刻,确实很兴奋,但是那两个都是基于别人研究的整理,只当是多加深了一下网络封包的理解

  下面这个是用到的协议,也可以自己去拦截看看是否现在已经改变,至少在今年三月的时候还是能正常用的

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace JI
{
    public static class Helper_QQ
    {
        /// <summary>
        /// 登录QQ
        /// </summary>
        public static string QQLogin = "VER=1.4&CON=1&CMD=Login&SEQ=QQSeq&UIN=QQNumber&PS=QQPassword&M5=1&LG=0&LC=812822641C978097&GD=EX4RLS2GFYGR6T1R&CKE=\r\n";
        /// <summary>
        /// QQ验证码
        /// </summary>
        public static string QQYanZheng = "VER=1.4&CON=1&CMD=VERIFYCODE&SEQ=QQSeq&UIN=QQNumber&SID=&XP=C4CA4238A0B92382&SC=2&VC=YanZhengMa\r\n";
        /// <summary>
        /// 隐身
        /// </summary>
        public static string QQYinShen = " VER=1.4&CON=1&CMD=Change_Stat&SEQ=QQSeq&UIN=QQNumber&SID=&XP=C4CA4238A0B92382&ST=40\r\n";
        /// <summary>
        /// 离开
        /// </summary>
        public static string QQLiKai = " VER=1.4&CON=1&CMD=Change_Stat&SEQ=QQSeq&UIN=QQNumber&SID=&XP=C4CA4238A0B92382&ST=30\r\n";
        /// <summary>
        /// 在线
        /// </summary>
        public static string QQZaiXian = "VER=1.4&CON=1&CMD=Change_Stat&SEQ=QQSeq&UIN=QQNumber&SID=&XP=C4CA4238A0B92382&ST=10\r\n";
        /// <summary>
        /// 注销
        /// </summary>
        public static string QQZhuXiao = "VER=1.4&CON=1&CMD=Logout&SEQ=QQSeq&UIN=QQNumber&SID=&XP=C4CA4238A0B92382\r\n";
        /// <summary>
        /// 获取取QQ在线好友
        /// </summary>
        public static string QQZaiXianHaoYou = "VER=1.4&CON=1&CMD=Query_Stat2&SEQ=QQSeq&UIN=QQNumber&SID=&XP=C4CA4238A0B92382&CM=2&UN=0\r\n";
        /// <summary>
        /// 发送消息
        /// </summary>
        public static string QQSentMessage = "VER=1.4&CON=1&CMD=CLTMSG&SEQ=QQSeq&UIN=QQNumber&SID=&XP=C4CA4238A0B92382&UN=HaoYou&MG=Message\r\n";
        /// <summary>
        /// 查看好友资料
        /// </summary>
        public static string QQHaoYouZiLiao = "VER=1.4&CON=1&CMD=GetInfo&SEQ=QQSeq&UIN=QQNumber&SID=&XP=C4CA4238A0B92382&LV=2&UN=HaoYou\r\n";
        /// <summary>
        /// 加好友
        /// </summary>
        public static string QQJiaHaoYou = "VER=1.4&CON=1&CMD=AddToList&SEQ=QQSeq&UIN=QQNumber&SID=&XP=C4CA4238A0B92382&UN=HaoYou\r\n";
        /// <summary>
        /// 验证好友信息
        /// </summary>
        public static string QQYanZhengHaoYou = "VER=1.4&CON=1&CMD=Ack_AddToList&SEQ=QQSeq&UIN=QQNumber&SID=&XP=C4CA4238A0B92382&UN=HaoYou&CD=2&RS=YanZheng\r\n";

        /// <summary>
        /// 转换密码为MD5
        /// </summary>
        /// <param name="toCryString"></param>
        /// <returns></returns>
        public static string MD5(string toCryString)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider hashmd5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            return BitConverter.ToString(hashmd5.ComputeHash(Encoding.Default.GetBytes(toCryString))).Replace("-", "").ToLower();
        }

    }

    public class QQ
    {
        public string QQNumber = null;
        public string QQPassword = null;
        public string QQZhuangTai = null;

        public enum QQzhuangtai
        {
            在线 = 1,
            隐身,
            离线
        }

        public void User(string number, string password)
        {
            this.QQNumber = number;
            this.QQPassword = password;
        }
        /// <summary>
        /// QQ登录
        /// </summary>
        /// <returns></returns>
        public Byte[] Login()
        {
            string SEQ = DateTime.Now.Ticks.ToString().Substring(7, 7);
            string PasswordMD5 = (this.QQPassword);
            string LoginString= Helper_QQ.QQLogin.Replace("QQSeq", SEQ).Replace("QQNumber", this.QQNumber).Replace("QQPassword", PasswordMD5);
            return System.Text.Encoding.UTF8.GetBytes(LoginString);

        }
        /// <summary>
        /// 验证码
        /// </summary>
        /// <param name="yanzheng"></param>
        /// <returns></returns>
        public Byte[] YanZheng(string yanzheng)
        {
            string SEQ = DateTime.Now.Ticks.ToString().Substring(7, 7);
            string yz = Helper_QQ.QQYanZheng.Replace("QQSeq", SEQ).Replace("QQNumber", this.QQNumber).Replace("YanZhengMa", yanzheng);
            return System.Text.Encoding.UTF8.GetBytes(yz);
        }
        /// <summary>
        /// 隐身
        /// </summary>
        /// <returns></returns>
        public Byte[] YinShen()
        {
            string SEQ = DateTime.Now.Ticks.ToString().Substring(7, 7);
            string ys = Helper_QQ.QQYinShen.Replace("QQSeq", SEQ).Replace("QQNumber", this.QQNumber);
            return System.Text.Encoding.UTF8.GetBytes(ys);
        }
        /// <summary>
        /// 离开
        /// </summary>
        /// <returns></returns>
        public Byte[] LiKai()
        {
            string SEQ = DateTime.Now.Ticks.ToString().Substring(7, 7);
            string lk = Helper_QQ.QQLiKai.Replace("QQSeq", SEQ).Replace("QQNumber", this.QQNumber);
            return System.Text.Encoding.UTF8.GetBytes(lk);
        }
        /// <summary>
        /// 在线
        /// </summary>
        /// <returns></returns>
        public Byte[] ZaiXian()
        {
            string SEQ = DateTime.Now.Ticks.ToString().Substring(7, 7);
            string zx = Helper_QQ.QQZaiXian.Replace("QQSeq", SEQ).Replace("QQNumber", this.QQNumber);
            return System.Text.Encoding.UTF8.GetBytes(zx);
        }
        /// <summary>
        ///注销
        /// </summary>
        /// <returns></returns>
        public Byte[] ZhuXiao()
        {
            string SEQ = DateTime.Now.Ticks.ToString().Substring(7, 7);
            string zx = Helper_QQ.QQZhuXiao.Replace("QQSeq", SEQ).Replace("QQNumber", this.QQNumber);
            return System.Text.Encoding.UTF8.GetBytes(zx);
        }
        /// <summary>
        /// 获取在线好友
        /// </summary>
        /// <param name="ZaiXianHaoYou"></param>
        /// <returns></returns>
        public Byte[] ZaiXianHaoYou()
        {
            string SEQ = DateTime.Now.Ticks.ToString().Substring(7, 7);
            string zxhy = Helper_QQ.QQZaiXianHaoYou.Replace("QQSeq", SEQ).Replace("QQNumber", this.QQNumber);
            return System.Text.Encoding.UTF8.GetBytes(zxhy);
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="SentMessage"></param>
        /// <returns></returns>
        public Byte[] SentMessage(string qqNumber,string message)
        {
            string SEQ = DateTime.Now.Ticks.ToString().Substring(7, 7);
            string sm = Helper_QQ.QQSentMessage.Replace("QQSeq", SEQ).Replace("QQNumber", this.QQNumber).Replace("HaoYou", qqNumber).Replace("Message", message);
            return System.Text.Encoding.UTF8.GetBytes(sm);
        }
        /// <summary>
        /// 获取好友资料
        /// </summary>
        /// <param name="qqNumber"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public Byte[] HaoYouZiLiao(string qqNumber)
        {
            string SEQ = DateTime.Now.Ticks.ToString().Substring(7, 7);
            string sm = Helper_QQ.QQHaoYouZiLiao.Replace("QQSeq", SEQ).Replace("QQNumber", this.QQNumber).Replace("HaoYou", qqNumber);
            return System.Text.Encoding.UTF8.GetBytes(sm);
        }

    }
}
复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace JI
{
    public static class Helper_QQ
    {
        /// <summary>
        /// 登录QQ
        /// </summary>
        public static string QQLogin = "VER=1.4&CON=1&CMD=Login&SEQ=QQSeq&UIN=QQNumber&PS=QQPassword&M5=1&LG=0&LC=812822641C978097&GD=EX4RLS2GFYGR6T1R&CKE=\r\n";
        /// <summary>
        /// QQ验证码
        /// </summary>
        public static string QQYanZheng = "VER=1.4&CON=1&CMD=VERIFYCODE&SEQ=QQSeq&UIN=QQNumber&SID=&XP=C4CA4238A0B92382&SC=2&VC=YanZhengMa\r\n";
        /// <summary>
        /// 隐身
        /// </summary>
        public static string QQYinShen = " VER=1.4&CON=1&CMD=Change_Stat&SEQ=QQSeq&UIN=QQNumber&SID=&XP=C4CA4238A0B92382&ST=40\r\n";
        /// <summary>
        /// 离开
        /// </summary>
        public static string QQLiKai = " VER=1.4&CON=1&CMD=Change_Stat&SEQ=QQSeq&UIN=QQNumber&SID=&XP=C4CA4238A0B92382&ST=30\r\n";
        /// <summary>
        /// 在线
        /// </summary>
        public static string QQZaiXian = "VER=1.4&CON=1&CMD=Change_Stat&SEQ=QQSeq&UIN=QQNumber&SID=&XP=C4CA4238A0B92382&ST=10\r\n";
        /// <summary>
        /// 注销
        /// </summary>
        public static string QQZhuXiao = "VER=1.4&CON=1&CMD=Logout&SEQ=QQSeq&UIN=QQNumber&SID=&XP=C4CA4238A0B92382\r\n";
        /// <summary>
        /// 获取取QQ在线好友
        /// </summary>
        public static string QQZaiXianHaoYou = "VER=1.4&CON=1&CMD=Query_Stat2&SEQ=QQSeq&UIN=QQNumber&SID=&XP=C4CA4238A0B92382&CM=2&UN=0\r\n";
        /// <summary>
        /// 发送消息
        /// </summary>
        public static string QQSentMessage = "VER=1.4&CON=1&CMD=CLTMSG&SEQ=QQSeq&UIN=QQNumber&SID=&XP=C4CA4238A0B92382&UN=HaoYou&MG=Message\r\n";
        /// <summary>
        /// 查看好友资料
        /// </summary>
        public static string QQHaoYouZiLiao = "VER=1.4&CON=1&CMD=GetInfo&SEQ=QQSeq&UIN=QQNumber&SID=&XP=C4CA4238A0B92382&LV=2&UN=HaoYou\r\n";
        /// <summary>
        /// 加好友
        /// </summary>
        public static string QQJiaHaoYou = "VER=1.4&CON=1&CMD=AddToList&SEQ=QQSeq&UIN=QQNumber&SID=&XP=C4CA4238A0B92382&UN=HaoYou\r\n";
        /// <summary>
        /// 验证好友信息
        /// </summary>
        public static string QQYanZhengHaoYou = "VER=1.4&CON=1&CMD=Ack_AddToList&SEQ=QQSeq&UIN=QQNumber&SID=&XP=C4CA4238A0B92382&UN=HaoYou&CD=2&RS=YanZheng\r\n";

        /// <summary>
        /// 转换密码为MD5
        /// </summary>
        /// <param name="toCryString"></param>
        /// <returns></returns>
        public static string MD5(string toCryString)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider hashmd5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            return BitConverter.ToString(hashmd5.ComputeHash(Encoding.Default.GetBytes(toCryString))).Replace("-", "").ToLower();
        }

    }

    public class QQ
    {
        public string QQNumber = null;
        public string QQPassword = null;
        public string QQZhuangTai = null;

        public enum QQzhuangtai
        {
            在线 = 1,
            隐身,
            离线
        }

        public void User(string number, string password)
        {
            this.QQNumber = number;
            this.QQPassword = password;
        }
        /// <summary>
        /// QQ登录
        /// </summary>
        /// <returns></returns>
        public Byte[] Login()
        {
            string SEQ = DateTime.Now.Ticks.ToString().Substring(7, 7);
            string PasswordMD5 = (this.QQPassword);
            string LoginString= Helper_QQ.QQLogin.Replace("QQSeq", SEQ).Replace("QQNumber", this.QQNumber).Replace("QQPassword", PasswordMD5);
            return System.Text.Encoding.UTF8.GetBytes(LoginString);

        }
        /// <summary>
        /// 验证码
        /// </summary>
        /// <param name="yanzheng"></param>
        /// <returns></returns>
        public Byte[] YanZheng(string yanzheng)
        {
            string SEQ = DateTime.Now.Ticks.ToString().Substring(7, 7);
            string yz = Helper_QQ.QQYanZheng.Replace("QQSeq", SEQ).Replace("QQNumber", this.QQNumber).Replace("YanZhengMa", yanzheng);
            return System.Text.Encoding.UTF8.GetBytes(yz);
        }
        /// <summary>
        /// 隐身
        /// </summary>
        /// <returns></returns>
        public Byte[] YinShen()
        {
            string SEQ = DateTime.Now.Ticks.ToString().Substring(7, 7);
            string ys = Helper_QQ.QQYinShen.Replace("QQSeq", SEQ).Replace("QQNumber", this.QQNumber);
            return System.Text.Encoding.UTF8.GetBytes(ys);
        }
        /// <summary>
        /// 离开
        /// </summary>
        /// <returns></returns>
        public Byte[] LiKai()
        {
            string SEQ = DateTime.Now.Ticks.ToString().Substring(7, 7);
            string lk = Helper_QQ.QQLiKai.Replace("QQSeq", SEQ).Replace("QQNumber", this.QQNumber);
            return System.Text.Encoding.UTF8.GetBytes(lk);
        }
        /// <summary>
        /// 在线
        /// </summary>
        /// <returns></returns>
        public Byte[] ZaiXian()
        {
            string SEQ = DateTime.Now.Ticks.ToString().Substring(7, 7);
            string zx = Helper_QQ.QQZaiXian.Replace("QQSeq", SEQ).Replace("QQNumber", this.QQNumber);
            return System.Text.Encoding.UTF8.GetBytes(zx);
        }
        /// <summary>
        ///注销
        /// </summary>
        /// <returns></returns>
        public Byte[] ZhuXiao()
        {
            string SEQ = DateTime.Now.Ticks.ToString().Substring(7, 7);
            string zx = Helper_QQ.QQZhuXiao.Replace("QQSeq", SEQ).Replace("QQNumber", this.QQNumber);
            return System.Text.Encoding.UTF8.GetBytes(zx);
        }
        /// <summary>
        /// 获取在线好友
        /// </summary>
        /// <param name="ZaiXianHaoYou"></param>
        /// <returns></returns>
        public Byte[] ZaiXianHaoYou()
        {
            string SEQ = DateTime.Now.Ticks.ToString().Substring(7, 7);
            string zxhy = Helper_QQ.QQZaiXianHaoYou.Replace("QQSeq", SEQ).Replace("QQNumber", this.QQNumber);
            return System.Text.Encoding.UTF8.GetBytes(zxhy);
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="SentMessage"></param>
        /// <returns></returns>
        public Byte[] SentMessage(string qqNumber,string message)
        {
            string SEQ = DateTime.Now.Ticks.ToString().Substring(7, 7);
            string sm = Helper_QQ.QQSentMessage.Replace("QQSeq", SEQ).Replace("QQNumber", this.QQNumber).Replace("HaoYou", qqNumber).Replace("Message", message);
            return System.Text.Encoding.UTF8.GetBytes(sm);
        }
        /// <summary>
        /// 获取好友资料
        /// </summary>
        /// <param name="qqNumber"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public Byte[] HaoYouZiLiao(string qqNumber)
        {
            string SEQ = DateTime.Now.Ticks.ToString().Substring(7, 7);
            string sm = Helper_QQ.QQHaoYouZiLiao.Replace("QQSeq", SEQ).Replace("QQNumber", this.QQNumber).Replace("HaoYou", qqNumber);
            return System.Text.Encoding.UTF8.GetBytes(sm);
        }

    }
}
复制代码

  这个是socket,感觉很垃圾的自己该,反正我现在感觉以前写的代码都很垃圾

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading;
using System.Net.Sockets;

namespace JI
{
    class Helper_Socket
    {
        public Thread tClient = null;
        public IPEndPoint pClient = null;
        public Socket sClient = null;
        public NetworkStream nsClient = null;
        public bool m_bConnectedClient = false;
        public  event EventHandler RecivedMessage;
        public string message;

        protected virtual void OnRecivedMessage()
        {
            var handler = RecivedMessage;
                if (handler != null)
                {
                    handler(this, EventArgs.Empty);
                }
            }
        public bool Connect(IPEndPoint server)
        {
            pClient = server;// new IPEndPoint(IPAddress.Parse("58.60.12.177"), 14000);
            sClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sClient.Connect(pClient);
            if (sClient.Connected)
            {
                nsClient = new NetworkStream(sClient);
                tClient = new Thread(new ThreadStart(this.ThreadListenClient));
                tClient.Start();
                m_bConnectedClient = true;
                return true;
            }
            return false;
        }

        public bool Sent(byte[] sentArray)
        {
            int length = sentArray.Length;
            if (sClient.Connected)
            {
                int sentNum = sClient.Send(sentArray, 0, length, SocketFlags.None);
                if (sentNum == length)
                { return true; }
                else
                { return false; }
            }
            return false;
        }

        public void Close()
        {
            sClient.Close();
        }

        public void ThreadListenClient()
        {
            string tmp = string.Empty;
            while (m_bConnectedClient)
            {
                try
                {
                    byte[] data = new byte[2056];
                    sClient.Receive(data);
                    var messagetemp = Encoding.UTF8.GetString(data).Trim();
                    message = messagetemp.Replace("\0", "");
                    if (message.Length > 0)
                    {
                        OnRecivedMessage();
                    }
                }
                catch
                {

                }
            }
        }

    }
}
复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading;
using System.Net.Sockets;

namespace JI
{
    class Helper_Socket
    {
        public Thread tClient = null;
        public IPEndPoint pClient = null;
        public Socket sClient = null;
        public NetworkStream nsClient = null;
        public bool m_bConnectedClient = false;
        public  event EventHandler RecivedMessage;
        public string message;

        protected virtual void OnRecivedMessage()
        {
            var handler = RecivedMessage;
                if (handler != null)
                {
                    handler(this, EventArgs.Empty);
                }
            }
        public bool Connect(IPEndPoint server)
        {
            pClient = server;// new IPEndPoint(IPAddress.Parse("58.60.12.177"), 14000);
            sClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sClient.Connect(pClient);
            if (sClient.Connected)
            {
                nsClient = new NetworkStream(sClient);
                tClient = new Thread(new ThreadStart(this.ThreadListenClient));
                tClient.Start();
                m_bConnectedClient = true;
                return true;
            }
            return false;
        }

        public bool Sent(byte[] sentArray)
        {
            int length = sentArray.Length;
            if (sClient.Connected)
            {
                int sentNum = sClient.Send(sentArray, 0, length, SocketFlags.None);
                if (sentNum == length)
                { return true; }
                else
                { return false; }
            }
            return false;
        }

        public void Close()
        {
            sClient.Close();
        }

        public void ThreadListenClient()
        {
            string tmp = string.Empty;
            while (m_bConnectedClient)
            {
                try
                {
                    byte[] data = new byte[2056];
                    sClient.Receive(data);
                    var messagetemp = Encoding.UTF8.GetString(data).Trim();
                    message = messagetemp.Replace("\0", "");
                    if (message.Length > 0)
                    {
                        OnRecivedMessage();
                    }
                }
                catch
                {

                }
            }
        }

    }
}
复制代码

  这个是帮助类,有抄袭的嫌疑,忘了抄谁的了,原作见谅

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media.Imaging;
using System.IO;
using System.Windows.Media;

namespace JI
{
    class Helper
    {
        /// <summary>
        /// 字符串转16进制字节数组
        /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        public static byte[] strToToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }

        /// <summary>
        /// 字节数组转16进制字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string byteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }

        /// <summary>
        /// 从汉字转换到16进制
        /// </summary>
        /// <param name="s"></param>
        /// <param name="charset">编码,如"utf-8","gb2312"</param>
        /// <param name="fenge">是否每字符用逗号分隔</param>
        /// <returns></returns>
        public static string ToHex(string s, string charset, bool fenge)
        {
            if ((s.Length % 2) != 0)
            {
                s += " ";//空格
                //throw new ArgumentException("s is not valid chinese string!");
            }
            System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
            byte[] bytes = chs.GetBytes(s);
            string str = "";
            for (int i = 0; i < bytes.Length; i++)
            {
                str += string.Format("{0:X}", bytes[i]);
                if (fenge && (i != bytes.Length - 1))
                {
                    str += string.Format("{0}", ",");
                }
            }
            return str.ToLower();
        }

        /// <summary>
        /// 从16进制转换成汉字
        /// </summary>
        /// <param name="hex"></param>
        /// <param name="charset">编码,如"utf-8","gb2312"</param>
        /// <returns></returns>
        public static string UnHex(string hex, string charset)
        {
            if (hex == null)
                throw new ArgumentNullException("hex");
            hex = hex.Replace(",", "");
            hex = hex.Replace("/n", "");
            hex = hex.Replace("//", "");
            hex = hex.Replace(" ", "");
            if (hex.Length % 2 != 0)
            {
                hex += "20";//空格
            }
            // 需要将 hex 转换成 byte 数组。 
            byte[] bytes = new byte[hex.Length / 2];

            for (int i = 0; i < bytes.Length; i++)
            {
                try
                {
                    // 每两个字符是一个 byte。 
                    bytes[i] = byte.Parse(hex.Substring(i * 2, 2),
                    System.Globalization.NumberStyles.HexNumber);
                }
                catch
                {
                    // Rethrow an exception with custom message. 
                    throw new ArgumentException("hex is not a valid hex number!", "hex");
                }
            }
            System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
            return chs.GetString(bytes);
        }

        /// <summary>
        /// 保存图片
        /// </summary>
        /// <param name="bitmap"></param>
        public static void SaveImageCapture(BitmapSource bitmap)
        {
            JpegBitmapEncoder encoder = new JpegBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bitmap));
            encoder.QualityLevel = 100;
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName = "Image";
            dlg.DefaultExt = ".Jpg";
            dlg.Filter = "Image (.jpg)|*.jpg";
            Nullable<bool> result = dlg.ShowDialog();
            if (result == true)
            {
                string filename = dlg.FileName;
                FileStream fstream = new FileStream(filename, FileMode.Create);
                encoder.Save(fstream);
                fstream.Close();
            }
        }
        /// <summary>
        /// 打开文件
        /// </summary>
        /// <returns></returns>
        public static  string Search()
        {
            string filPath = string.Empty;
            System.Windows.Forms.OpenFileDialog openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
            openFileDialog1.Filter = "图片文件(*.jpg,*.jpeg,*.png,*.bmp)|*.jpg;*.jpeg;*.png;*.bmp";
            openFileDialog1.FilterIndex = 1;
            openFileDialog1.RestoreDirectory = true;
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                filPath = openFileDialog1.FileName;
            }
            else
            { }
            return filPath;
        }

        /// <summary>
        /// 打开图片
        /// </summary>
        /// <param name="bitmap"></param>
        /// <returns></returns>
        public static ImageSource ToConBmpToImSour(System.Drawing.Bitmap bitmap)
        {
            MemoryStream stream = new MemoryStream();
            bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
            ImageBrush imageBrush = new ImageBrush();
            ImageSourceConverter imageSourceConverter = new ImageSourceConverter();
            imageBrush.ImageSource = (ImageSource)imageSourceConverter.ConvertFrom(stream);
            return imageBrush.ImageSource;
        }

        /// <summary>
        /// 创建Image控件
        /// </summary>
        /// <param name="imageSource"></param>
        /// <returns></returns>
        public static System.Windows.Controls.Image CreatImage(ImageSource imageSource)
        {
            System.Windows.Controls.Image image = new System.Windows.Controls.Image();
            image.Source = imageSource;
            image.Stretch = System.Windows.Media.Stretch.Fill;
            return image;
        }
    }
}
复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media.Imaging;
using System.IO;
using System.Windows.Media;

namespace JI
{
    class Helper
    {
        /// <summary>
        /// 字符串转16进制字节数组
        /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        public static byte[] strToToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }

        /// <summary>
        /// 字节数组转16进制字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string byteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }

        /// <summary>
        /// 从汉字转换到16进制
        /// </summary>
        /// <param name="s"></param>
        /// <param name="charset">编码,如"utf-8","gb2312"</param>
        /// <param name="fenge">是否每字符用逗号分隔</param>
        /// <returns></returns>
        public static string ToHex(string s, string charset, bool fenge)
        {
            if ((s.Length % 2) != 0)
            {
                s += " ";//空格
                //throw new ArgumentException("s is not valid chinese string!");
            }
            System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
            byte[] bytes = chs.GetBytes(s);
            string str = "";
            for (int i = 0; i < bytes.Length; i++)
            {
                str += string.Format("{0:X}", bytes[i]);
                if (fenge && (i != bytes.Length - 1))
                {
                    str += string.Format("{0}", ",");
                }
            }
            return str.ToLower();
        }

        /// <summary>
        /// 从16进制转换成汉字
        /// </summary>
        /// <param name="hex"></param>
        /// <param name="charset">编码,如"utf-8","gb2312"</param>
        /// <returns></returns>
        public static string UnHex(string hex, string charset)
        {
            if (hex == null)
                throw new ArgumentNullException("hex");
            hex = hex.Replace(",", "");
            hex = hex.Replace("/n", "");
            hex = hex.Replace("//", "");
            hex = hex.Replace(" ", "");
            if (hex.Length % 2 != 0)
            {
                hex += "20";//空格
            }
            // 需要将 hex 转换成 byte 数组。 
            byte[] bytes = new byte[hex.Length / 2];

            for (int i = 0; i < bytes.Length; i++)
            {
                try
                {
                    // 每两个字符是一个 byte。 
                    bytes[i] = byte.Parse(hex.Substring(i * 2, 2),
                    System.Globalization.NumberStyles.HexNumber);
                }
                catch
                {
                    // Rethrow an exception with custom message. 
                    throw new ArgumentException("hex is not a valid hex number!", "hex");
                }
            }
            System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
            return chs.GetString(bytes);
        }

        /// <summary>
        /// 保存图片
        /// </summary>
        /// <param name="bitmap"></param>
        public static void SaveImageCapture(BitmapSource bitmap)
        {
            JpegBitmapEncoder encoder = new JpegBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bitmap));
            encoder.QualityLevel = 100;
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName = "Image";
            dlg.DefaultExt = ".Jpg";
            dlg.Filter = "Image (.jpg)|*.jpg";
            Nullable<bool> result = dlg.ShowDialog();
            if (result == true)
            {
                string filename = dlg.FileName;
                FileStream fstream = new FileStream(filename, FileMode.Create);
                encoder.Save(fstream);
                fstream.Close();
            }
        }
        /// <summary>
        /// 打开文件
        /// </summary>
        /// <returns></returns>
        public static  string Search()
        {
            string filPath = string.Empty;
            System.Windows.Forms.OpenFileDialog openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
            openFileDialog1.Filter = "图片文件(*.jpg,*.jpeg,*.png,*.bmp)|*.jpg;*.jpeg;*.png;*.bmp";
            openFileDialog1.FilterIndex = 1;
            openFileDialog1.RestoreDirectory = true;
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                filPath = openFileDialog1.FileName;
            }
            else
            { }
            return filPath;
        }

        /// <summary>
        /// 打开图片
        /// </summary>
        /// <param name="bitmap"></param>
        /// <returns></returns>
        public static ImageSource ToConBmpToImSour(System.Drawing.Bitmap bitmap)
        {
            MemoryStream stream = new MemoryStream();
            bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
            ImageBrush imageBrush = new ImageBrush();
            ImageSourceConverter imageSourceConverter = new ImageSourceConverter();
            imageBrush.ImageSource = (ImageSource)imageSourceConverter.ConvertFrom(stream);
            return imageBrush.ImageSource;
        }

        /// <summary>
        /// 创建Image控件
        /// </summary>
        /// <param name="imageSource"></param>
        /// <returns></returns>
        public static System.Windows.Controls.Image CreatImage(ImageSource imageSource)
        {
            System.Windows.Controls.Image image = new System.Windows.Controls.Image();
            image.Source = imageSource;
            image.Stretch = System.Windows.Media.Stretch.Fill;
            return image;
        }
    }
}
复制代码

  这个是主界面处理,我那时候还不懂得封装和拆分,也不知道什么分层,全把wpf当作winform使了,原谅一个初学者的无知……

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using JI;
using System.Net;
using System.IO;

namespace QQ__迹
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        #region 参数设置
        QQ qq = null;
        string re = string.Empty;
        Helper_Socket socket = null;
        double width = 0; double height = 0;
        WaterEffect effect;
        Point point;
        int a = 0;
        const int shuxin = 1000 * 30;
        List<string> HaoYouListTemp = new List<string>();
        List<string> HaoYouListZiLiao = new List<string>();
        int hyconut = 0;
        Image image = new Image();
        int xianshinum = 1;
        #endregion

        public MainWindow()
        {
            InitializeComponent();

            ToBindTimerEvent();
            this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            XianShi(0);
            user.Text = "12345678";
            psw.Password = "12345678";
            effect = new WaterEffect(120, 100);

            Media.Child = image;
            BitmapImage bi3 = new BitmapImage();
            bi3.BeginInit();
            bi3.UriSource = new Uri("IMAG0460.jpg", UriKind.Relative);
            bi3.EndInit();
            image.Stretch = Stretch.Fill;
            image.Source = bi3;

            Media.Effect = effect;
        }

        public void ToBindTimerEvent()
        {
            DispatcherTimer timer = new DispatcherTimer { Interval = new TimeSpan(0, 0, 0, 0, 1) };
            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();
        }
        public void timer_Tick(object sender, EventArgs e)
        {
            a++;
            if (a == shuxin)
            {
                if (qq != null && socket.m_bConnectedClient)
                {
                    socket.Sent(qq.ZaiXian());
                }
                a = 0;
            }
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            if (socket != null)
            {
                socket.m_bConnectedClient = false;
                socket.Close();
            }
            base.OnClosing(e);
        }

        private void dl_MouseDown(object sender, MouseButtonEventArgs e)
        {
            socket = new Helper_Socket();
            IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("58.60.12.177"), 14000);
            var con = socket.Connect(serverEndPoint);
            if (con)
            {
                socket.RecivedMessage += new EventHandler(socket_RecivedMessage);
            }
            else
            {
                MessageBox.Show("请检查网络联通性", "登录失败");
                this.Close();
            }
            string num = user.Text.Trim();
            string pswd = JI.Helper_QQ.MD5(psw.Password);
            qq = new QQ();
            qq.User(num, pswd);
            bool chack = false;
            if (socket.m_bConnectedClient)
            {
                chack = socket.Sent(qq.Login());
            }
        }

        private void socket_RecivedMessage(object sender, EventArgs e)
        {
            var messageSocket = (Helper_Socket)sender;
            try
            {
                #region 登录处理
                #region 验证码处理
                if (messageSocket.message.Contains("CMD=VERIFYCODE") && !messageSocket.message.Contains("RE=1") && !messageSocket.message.Contains("RS=0"))
                {
                    //验证码处理
                    string imageStrem = (messageSocket.message.Split(new string[] { "&VC=" }, StringSplitOptions.RemoveEmptyEntries))[1];//(new char[] { '&', 'V', 'C' });
                    var imageByte = (imageStrem.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries))[0];
                    using (MemoryStream ms = new MemoryStream(Helper.strToToHexByte(imageByte.Trim())))
                    {
                        BitmapDecoder decoder = BitmapDecoder.Create(ms, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                        var img = decoder.Frames[0];
                        ImageSourceConverter imageSourceConverter = new ImageSourceConverter();
                        img.Freeze();
                        Dispatcher.Invoke((Action)delegate
                        {
                            griddl.Visibility = System.Windows.Visibility.Collapsed;
                            gridyz.Opacity = 1;
                            gridyz.Visibility = System.Windows.Visibility.Visible;
                            imageYanZheng.Source = img;
                            //  Helper.SaveImageCapture((BitmapSource)imageSourceConverter.ConvertFrom(ms));
                        });
                    }
                }
                #endregion
                #region 登录成功
                else if (messageSocket.message.Contains("RS=0") && messageSocket.message.Contains("CMD=Login"))
                {
                    Dispatcher.Invoke((Action)delegate
                    {
                        gridyz.Visibility = System.Windows.Visibility.Collapsed;
                        griddl.Visibility = System.Windows.Visibility.Collapsed;
                        XianShi(1);

                        loginQQ.Content = qq.QQNumber;
                        qq.QQZhuangTai = (QQ.QQzhuangtai.在线).ToString();
                        ztQQ.Content = qq.QQZhuangTai;
                    });
                    if (qq != null && socket.m_bConnectedClient)
                    {
                        HaoYouListTemp.Clear();
                        HaoYouListZiLiao.Clear();
                        socket.Sent(qq.ZaiXianHaoYou());
                    }
                }
                #endregion
                #region 密码错误
                else if (messageSocket.message.Contains("RA=Password error!"))
                {
                    MessageBox.Show("密码错误", "登录失败");
                    Dispatcher.Invoke((Action)delegate
                    {
                        gridyz.Visibility = System.Windows.Visibility.Collapsed;
                        griddl.Visibility = System.Windows.Visibility.Visible;
                        psw.Password = "";
                    });
                }
                #endregion
                #endregion
                #region 消息处理
                #region 获取在线好友
                if (messageSocket.message.Contains("CMD=QUERY_STAT2") && messageSocket.message.Contains("RES=0"))
                {
                    var qqList = messageSocket.message.Split(new string[] { "&UN=" }, 10, StringSplitOptions.RemoveEmptyEntries);
                    string ListTemp = string.Empty;
                    foreach (var list in qqList)
                    {
                        if (!list.Contains("&MG="))
                        {
                            ListTemp = (list.Replace("&", ""));
                        }
                    }
                    var haoyouList = (ListTemp.Split((new string[] { "\r\n" }), StringSplitOptions.RemoveEmptyEntries))[0].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                    if (qq != null && socket.m_bConnectedClient)
                    {
                        HaoYouListTemp.AddRange(haoyouList);
                        HaoYouListTemp.ForEach(haoy => { socket.Sent(qq.HaoYouZiLiao(haoy)); });
                    }
                    ////好友列表
                    Dispatcher.Invoke((Action)delegate
                    {
                        listBoxhyl.ItemsSource = HaoYouListTemp;
                    });
                }
                #endregion
                #region 状态更改
                if (messageSocket.message.Contains("CMD=Change_Stat") && messageSocket.message.Contains("RES=0"))// && messageSocket.message.Contains("UIN=" + qq.QQNumber))
                {
                    Dispatcher.Invoke((Action)delegate
                    {
                        ztQQ.Content = qq.QQZhuangTai;
                    });
                }
                #endregion
                #region 系统消息
                if (messageSocket.message.Contains("CMD=Server_Msg") && messageSocket.message.Contains("&MG=") && messageSocket.message.Contains("RES=0"))// && messageSocket.message.Contains("UIN=" + qq.QQNumber))
                {
                    var msgList = messageSocket.message.Split((new string[] { "\r\n" }), StringSplitOptions.RemoveEmptyEntries);
                    List<string[]> message = new List<string[]>();
                    foreach (var str in msgList)
                    {
                        message.Add(str.Split(new string[] { "&UN=", "&MG=" }, StringSplitOptions.RemoveEmptyEntries));
                    }
                    message.ForEach(s =>
                    {
                        Dispatcher.Invoke((Action)delegate
                     {
                         if (s.Length > 2)
                         {
                             var name = string.Empty;
                             HaoYouListZiLiao.ForEach(who =>
                             {
                                 if (who.Contains(s[1].ToString()))
                                 { name = who; }
                             });
                             textBlockr.Text += name + NowTime() + " 对我说:" + s[2].ToString() + System.Environment.NewLine;
                         }
                     });
                    });
                }
                #endregion
                #region 好友资料
                //if (messageSocket.message.Contains("CMD=GETINFO") && messageSocket.message.Contains("&UN=") && messageSocket.message.Contains("&NK=") && messageSocket.message.Contains("&RES=0&"))
                //{

                //    var haoyouziliao = messageSocket.message.Split((new string[] { "&UN=", "&NK=", "&PR=", "\r\n" }), StringSplitOptions.RemoveEmptyEntries);
                //    //Dispatcher.Invoke((Action)delegate
                //    //        {
                //                HaoYouListTemp.ForEach(hyzl =>
                //                    {
                //                        if (hyzl == haoyouziliao[1])
                //                        {
                //                            hyzl += " " + haoyouziliao[2];
                //                            HaoYouListZiLiao.Add(hyzl);
                //                        }
                //                    });
                //                hyconut++;
                //                if (hyconut == HaoYouListTemp.Count)
                //                {
                //                    hyconut = 0;

                //                    listBoxhyl.ItemsSource = HaoYouListZiLiao;

                //                }
                //            //});
                //}
                #endregion
                #endregion
            }
            catch { }
        }
        private void tc_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this.Close();
        }

        private void fsyz_MouseDown(object sender, MouseButtonEventArgs e)
        {
            var yanzheng = qq.YanZheng(yzm.Text.Trim());
            if (socket.m_bConnectedClient)
            {
                socket.Sent(yanzheng);
            }
        }

        private void sent_MouseDown(object sender, MouseButtonEventArgs e)
        {
            string cz = caozuo.Text;
            string msg = textBlocks.Text;
            var who = textBox1.Text.Trim();

            if (qq != null && socket.m_bConnectedClient)
            {
                if (cz == "发送" && msg.Length > 0 && who.Length > 0)
                {
                    string sentto ="";
                    try {sentto = textBox1.Text.Remove(10).Trim();}
                    catch { sentto = textBox1.Text.Trim(); }
                   
                    if (sentto.Length > 0)
                    {
                        socket.Sent(qq.SentMessage(sentto, msg));
                        textBlockr.Text += "" + NowTime() + "" + who + " 说:" + msg + System.Environment.NewLine;
                        textBlocks.Text = "";
                    }
                }
                if (cz == "退出")
                {
                    this.Close();
                }

                if (cz == (QQ.QQzhuangtai.隐身).ToString())
                {
                    socket.Sent(qq.YinShen());
                    qq.QQZhuangTai = cz;
                }
                else if (cz == (QQ.QQzhuangtai.离线).ToString())
                {
                    socket.Sent(qq.LiKai());
                    qq.QQZhuangTai = cz;

                }
                else if (cz == (QQ.QQzhuangtai.在线).ToString())
                {
                    socket.Sent(qq.ZaiXian());
                    qq.QQZhuangTai = cz;
                }
            }
        }

        private void listBoxhyl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            textBox1.Text = listBoxhyl.SelectedValue.ToString();
        }

        private void sb_MouseDown(object sender, MouseButtonEventArgs e)
        {
            point = e.GetPosition(MainGrid);
            width = Media.ActualWidth;
            height = Media.ActualHeight;
            if (width > 0 && height > 0)
            {
                effect.Drop((float)(point.X / width), (float)(point.Y / height));
            }
        }

        private void jhy_MouseDown(object sender, MouseButtonEventArgs e)
        {
            var sentto = textBox1.Text.Trim();
            if (qq != null && socket.m_bConnectedClient && sentto.Length > 0)
            {
                socket.Sent(qq.HaoYouZiLiao(sentto));
            }
        }

        private void sx_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (qq != null && socket.m_bConnectedClient)
            {
                HaoYouListTemp.Clear();
                HaoYouListZiLiao.Clear();
                socket.Sent(qq.ZaiXianHaoYou());
            }
        }

        private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                #region 换图
                bool isShift = false;
                string path = string.Empty;
                System.Windows.Input.KeyboardDevice kd = e.KeyboardDevice;
                if ((kd.GetKeyStates(Key.LeftCtrl) & System.Windows.Input.KeyStates.Down) > 0 &&
                    (kd.GetKeyStates(Key.B) & System.Windows.Input.KeyStates.Down) > 0 ||
                    (kd.GetKeyStates(Key.RightCtrl) & System.Windows.Input.KeyStates.Down) > 0 &&
                    (kd.GetKeyStates(Key.B) & System.Windows.Input.KeyStates.Down) > 0
                    )
                {
                    path = Helper.Search();
                    isShift = true;
                }

                if (isShift && path.Length > 0)
                {
                    image.Source = Helper.ToConBmpToImSour(new System.Drawing.Bitmap(path));
                    isShift = false;
                }
                #endregion

                #region 隐藏
                 bool  boolyincang=false;
            if ((kd.GetKeyStates(Key.LeftCtrl) & System.Windows.Input.KeyStates.Down) > 0 &&
                (kd.GetKeyStates(Key.LeftAlt) & System.Windows.Input.KeyStates.Down) > 0&&
                (kd.GetKeyStates(Key.Z) & System.Windows.Input.KeyStates.Down) > 0)
            {
                boolyincang =true;
                xianshinum *= -1;
            }
            

            if (boolyincang)
            {
                XianShi(xianshinum);
                boolyincang = false;
            }
                #endregion
            }
            catch { }

        }

        private void textBlockr_TextChanged(object sender, TextChangedEventArgs e)
        {
            textBlocks.Focus();
        }

        public string NowTime()
        {
            return DateTime.Now.ToString().Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)[1];
        }

        private void textBlocks_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            bool isShift = false;
            System.Windows.Input.KeyboardDevice kd = e.KeyboardDevice;
            if ((kd.GetKeyStates(Key.RightCtrl) & System.Windows.Input.KeyStates.Down) > 0 &&
                (kd.GetKeyStates(Key.Enter) & System.Windows.Input.KeyStates.Down) > 0 )
            {
                isShift = true;
            }
            if ((kd.GetKeyStates(Key.LeftAlt) & System.Windows.Input.KeyStates.Down) > 0 &&
               (kd.GetKeyStates(Key.S) & System.Windows.Input.KeyStates.Down) > 0)
            {
                isShift = true;
            }

            if (isShift)
            {
                caozuo.Text = "发送";
                string cz = caozuo.Text;
                string msg = textBlocks.Text;
                var who = textBox1.Text.Trim();

                if (qq != null && socket.m_bConnectedClient)
                {
                    if (cz == "发送" && msg.Length > 0 && who.Length > 0)
                    {
                        var sentto = textBox1.Text.Remove(10).Trim();
                        if (sentto.Length > 0)
                        {
                            socket.Sent(qq.SentMessage(sentto, msg));
                            textBlockr.Text += "" + NowTime() + "" + who + " 说:" + msg + System.Environment.NewLine;
                            textBlocks.Text = "";
                        }
                    }
                }
                isShift = false;
            }
        }
    }
}
复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using JI;
using System.Net;
using System.IO;

namespace QQ__迹
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        #region 参数设置
        QQ qq = null;
        string re = string.Empty;
        Helper_Socket socket = null;
        double width = 0; double height = 0;
        WaterEffect effect;
        Point point;
        int a = 0;
        const int shuxin = 1000 * 30;
        List<string> HaoYouListTemp = new List<string>();
        List<string> HaoYouListZiLiao = new List<string>();
        int hyconut = 0;
        Image image = new Image();
        int xianshinum = 1;
        #endregion

        public MainWindow()
        {
            InitializeComponent();

            ToBindTimerEvent();
            this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            XianShi(0);
            user.Text = "12345678";
            psw.Password = "12345678";
            effect = new WaterEffect(120, 100);

            Media.Child = image;
            BitmapImage bi3 = new BitmapImage();
            bi3.BeginInit();
            bi3.UriSource = new Uri("IMAG0460.jpg", UriKind.Relative);
            bi3.EndInit();
            image.Stretch = Stretch.Fill;
            image.Source = bi3;

            Media.Effect = effect;
        }

        public void ToBindTimerEvent()
        {
            DispatcherTimer timer = new DispatcherTimer { Interval = new TimeSpan(0, 0, 0, 0, 1) };
            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();
        }
        public void timer_Tick(object sender, EventArgs e)
        {
            a++;
            if (a == shuxin)
            {
                if (qq != null && socket.m_bConnectedClient)
                {
                    socket.Sent(qq.ZaiXian());
                }
                a = 0;
            }
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            if (socket != null)
            {
                socket.m_bConnectedClient = false;
                socket.Close();
            }
            base.OnClosing(e);
        }

        private void dl_MouseDown(object sender, MouseButtonEventArgs e)
        {
            socket = new Helper_Socket();
            IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("58.60.12.177"), 14000);
            var con = socket.Connect(serverEndPoint);
            if (con)
            {
                socket.RecivedMessage += new EventHandler(socket_RecivedMessage);
            }
            else
            {
                MessageBox.Show("请检查网络联通性", "登录失败");
                this.Close();
            }
            string num = user.Text.Trim();
            string pswd = JI.Helper_QQ.MD5(psw.Password);
            qq = new QQ();
            qq.User(num, pswd);
            bool chack = false;
            if (socket.m_bConnectedClient)
            {
                chack = socket.Sent(qq.Login());
            }
        }

        private void socket_RecivedMessage(object sender, EventArgs e)
        {
            var messageSocket = (Helper_Socket)sender;
            try
            {
                #region 登录处理
                #region 验证码处理
                if (messageSocket.message.Contains("CMD=VERIFYCODE") && !messageSocket.message.Contains("RE=1") && !messageSocket.message.Contains("RS=0"))
                {
                    //验证码处理
                    string imageStrem = (messageSocket.message.Split(new string[] { "&VC=" }, StringSplitOptions.RemoveEmptyEntries))[1];//(new char[] { '&', 'V', 'C' });
                    var imageByte = (imageStrem.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries))[0];
                    using (MemoryStream ms = new MemoryStream(Helper.strToToHexByte(imageByte.Trim())))
                    {
                        BitmapDecoder decoder = BitmapDecoder.Create(ms, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                        var img = decoder.Frames[0];
                        ImageSourceConverter imageSourceConverter = new ImageSourceConverter();
                        img.Freeze();
                        Dispatcher.Invoke((Action)delegate
                        {
                            griddl.Visibility = System.Windows.Visibility.Collapsed;
                            gridyz.Opacity = 1;
                            gridyz.Visibility = System.Windows.Visibility.Visible;
                            imageYanZheng.Source = img;
                            //  Helper.SaveImageCapture((BitmapSource)imageSourceConverter.ConvertFrom(ms));
                        });
                    }
                }
                #endregion
                #region 登录成功
                else if (messageSocket.message.Contains("RS=0") && messageSocket.message.Contains("CMD=Login"))
                {
                    Dispatcher.Invoke((Action)delegate
                    {
                        gridyz.Visibility = System.Windows.Visibility.Collapsed;
                        griddl.Visibility = System.Windows.Visibility.Collapsed;
                        XianShi(1);

                        loginQQ.Content = qq.QQNumber;
                        qq.QQZhuangTai = (QQ.QQzhuangtai.在线).ToString();
                        ztQQ.Content = qq.QQZhuangTai;
                    });
                    if (qq != null && socket.m_bConnectedClient)
                    {
                        HaoYouListTemp.Clear();
                        HaoYouListZiLiao.Clear();
                        socket.Sent(qq.ZaiXianHaoYou());
                    }
                }
                #endregion
                #region 密码错误
                else if (messageSocket.message.Contains("RA=Password error!"))
                {
                    MessageBox.Show("密码错误", "登录失败");
                    Dispatcher.Invoke((Action)delegate
                    {
                        gridyz.Visibility = System.Windows.Visibility.Collapsed;
                        griddl.Visibility = System.Windows.Visibility.Visible;
                        psw.Password = "";
                    });
                }
                #endregion
                #endregion
                #region 消息处理
                #region 获取在线好友
                if (messageSocket.message.Contains("CMD=QUERY_STAT2") && messageSocket.message.Contains("RES=0"))
                {
                    var qqList = messageSocket.message.Split(new string[] { "&UN=" }, 10, StringSplitOptions.RemoveEmptyEntries);
                    string ListTemp = string.Empty;
                    foreach (var list in qqList)
                    {
                        if (!list.Contains("&MG="))
                        {
                            ListTemp = (list.Replace("&", ""));
                        }
                    }
                    var haoyouList = (ListTemp.Split((new string[] { "\r\n" }), StringSplitOptions.RemoveEmptyEntries))[0].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                    if (qq != null && socket.m_bConnectedClient)
                    {
                        HaoYouListTemp.AddRange(haoyouList);
                        HaoYouListTemp.ForEach(haoy => { socket.Sent(qq.HaoYouZiLiao(haoy)); });
                    }
                    ////好友列表
                    Dispatcher.Invoke((Action)delegate
                    {
                        listBoxhyl.ItemsSource = HaoYouListTemp;
                    });
                }
                #endregion
                #region 状态更改
                if (messageSocket.message.Contains("CMD=Change_Stat") && messageSocket.message.Contains("RES=0"))// && messageSocket.message.Contains("UIN=" + qq.QQNumber))
                {
                    Dispatcher.Invoke((Action)delegate
                    {
                        ztQQ.Content = qq.QQZhuangTai;
                    });
                }
                #endregion
                #region 系统消息
                if (messageSocket.message.Contains("CMD=Server_Msg") && messageSocket.message.Contains("&MG=") && messageSocket.message.Contains("RES=0"))// && messageSocket.message.Contains("UIN=" + qq.QQNumber))
                {
                    var msgList = messageSocket.message.Split((new string[] { "\r\n" }), StringSplitOptions.RemoveEmptyEntries);
                    List<string[]> message = new List<string[]>();
                    foreach (var str in msgList)
                    {
                        message.Add(str.Split(new string[] { "&UN=", "&MG=" }, StringSplitOptions.RemoveEmptyEntries));
                    }
                    message.ForEach(s =>
                    {
                        Dispatcher.Invoke((Action)delegate
                     {
                         if (s.Length > 2)
                         {
                             var name = string.Empty;
                             HaoYouListZiLiao.ForEach(who =>
                             {
                                 if (who.Contains(s[1].ToString()))
                                 { name = who; }
                             });
                             textBlockr.Text += name + NowTime() + " 对我说:" + s[2].ToString() + System.Environment.NewLine;
                         }
                     });
                    });
                }
                #endregion
                #region 好友资料
                //if (messageSocket.message.Contains("CMD=GETINFO") && messageSocket.message.Contains("&UN=") && messageSocket.message.Contains("&NK=") && messageSocket.message.Contains("&RES=0&"))
                //{

                //    var haoyouziliao = messageSocket.message.Split((new string[] { "&UN=", "&NK=", "&PR=", "\r\n" }), StringSplitOptions.RemoveEmptyEntries);
                //    //Dispatcher.Invoke((Action)delegate
                //    //        {
                //                HaoYouListTemp.ForEach(hyzl =>
                //                    {
                //                        if (hyzl == haoyouziliao[1])
                //                        {
                //                            hyzl += " " + haoyouziliao[2];
                //                            HaoYouListZiLiao.Add(hyzl);
                //                        }
                //                    });
                //                hyconut++;
                //                if (hyconut == HaoYouListTemp.Count)
                //                {
                //                    hyconut = 0;

                //                    listBoxhyl.ItemsSource = HaoYouListZiLiao;

                //                }
                //            //});
                //}
                #endregion
                #endregion
            }
            catch { }
        }
        private void tc_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this.Close();
        }

        private void fsyz_MouseDown(object sender, MouseButtonEventArgs e)
        {
            var yanzheng = qq.YanZheng(yzm.Text.Trim());
            if (socket.m_bConnectedClient)
            {
                socket.Sent(yanzheng);
            }
        }

        private void sent_MouseDown(object sender, MouseButtonEventArgs e)
        {
            string cz = caozuo.Text;
            string msg = textBlocks.Text;
            var who = textBox1.Text.Trim();

            if (qq != null && socket.m_bConnectedClient)
            {
                if (cz == "发送" && msg.Length > 0 && who.Length > 0)
                {
                    string sentto ="";
                    try {sentto = textBox1.Text.Remove(10).Trim();}
                    catch { sentto = textBox1.Text.Trim(); }
                   
                    if (sentto.Length > 0)
                    {
                        socket.Sent(qq.SentMessage(sentto, msg));
                        textBlockr.Text += "" + NowTime() + "" + who + " 说:" + msg + System.Environment.NewLine;
                        textBlocks.Text = "";
                    }
                }
                if (cz == "退出")
                {
                    this.Close();
                }

                if (cz == (QQ.QQzhuangtai.隐身).ToString())
                {
                    socket.Sent(qq.YinShen());
                    qq.QQZhuangTai = cz;
                }
                else if (cz == (QQ.QQzhuangtai.离线).ToString())
                {
                    socket.Sent(qq.LiKai());
                    qq.QQZhuangTai = cz;

                }
                else if (cz == (QQ.QQzhuangtai.在线).ToString())
                {
                    socket.Sent(qq.ZaiXian());
                    qq.QQZhuangTai = cz;
                }
            }
        }

        private void listBoxhyl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            textBox1.Text = listBoxhyl.SelectedValue.ToString();
        }

        private void sb_MouseDown(object sender, MouseButtonEventArgs e)
        {
            point = e.GetPosition(MainGrid);
            width = Media.ActualWidth;
            height = Media.ActualHeight;
            if (width > 0 && height > 0)
            {
                effect.Drop((float)(point.X / width), (float)(point.Y / height));
            }
        }

        private void jhy_MouseDown(object sender, MouseButtonEventArgs e)
        {
            var sentto = textBox1.Text.Trim();
            if (qq != null && socket.m_bConnectedClient && sentto.Length > 0)
            {
                socket.Sent(qq.HaoYouZiLiao(sentto));
            }
        }

        private void sx_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (qq != null && socket.m_bConnectedClient)
            {
                HaoYouListTemp.Clear();
                HaoYouListZiLiao.Clear();
                socket.Sent(qq.ZaiXianHaoYou());
            }
        }

        private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                #region 换图
                bool isShift = false;
                string path = string.Empty;
                System.Windows.Input.KeyboardDevice kd = e.KeyboardDevice;
                if ((kd.GetKeyStates(Key.LeftCtrl) & System.Windows.Input.KeyStates.Down) > 0 &&
                    (kd.GetKeyStates(Key.B) & System.Windows.Input.KeyStates.Down) > 0 ||
                    (kd.GetKeyStates(Key.RightCtrl) & System.Windows.Input.KeyStates.Down) > 0 &&
                    (kd.GetKeyStates(Key.B) & System.Windows.Input.KeyStates.Down) > 0
                    )
                {
                    path = Helper.Search();
                    isShift = true;
                }

                if (isShift && path.Length > 0)
                {
                    image.Source = Helper.ToConBmpToImSour(new System.Drawing.Bitmap(path));
                    isShift = false;
                }
                #endregion

                #region 隐藏
                 bool  boolyincang=false;
            if ((kd.GetKeyStates(Key.LeftCtrl) & System.Windows.Input.KeyStates.Down) > 0 &&
                (kd.GetKeyStates(Key.LeftAlt) & System.Windows.Input.KeyStates.Down) > 0&&
                (kd.GetKeyStates(Key.Z) & System.Windows.Input.KeyStates.Down) > 0)
            {
                boolyincang =true;
                xianshinum *= -1;
            }
            

            if (boolyincang)
            {
                XianShi(xianshinum);
                boolyincang = false;
            }
                #endregion
            }
            catch { }

        }

        private void textBlockr_TextChanged(object sender, TextChangedEventArgs e)
        {
            textBlocks.Focus();
        }

        public string NowTime()
        {
            return DateTime.Now.ToString().Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)[1];
        }

        private void textBlocks_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            bool isShift = false;
            System.Windows.Input.KeyboardDevice kd = e.KeyboardDevice;
            if ((kd.GetKeyStates(Key.RightCtrl) & System.Windows.Input.KeyStates.Down) > 0 &&
                (kd.GetKeyStates(Key.Enter) & System.Windows.Input.KeyStates.Down) > 0 )
            {
                isShift = true;
            }
            if ((kd.GetKeyStates(Key.LeftAlt) & System.Windows.Input.KeyStates.Down) > 0 &&
               (kd.GetKeyStates(Key.S) & System.Windows.Input.KeyStates.Down) > 0)
            {
                isShift = true;
            }

            if (isShift)
            {
                caozuo.Text = "发送";
                string cz = caozuo.Text;
                string msg = textBlocks.Text;
                var who = textBox1.Text.Trim();

                if (qq != null && socket.m_bConnectedClient)
                {
                    if (cz == "发送" && msg.Length > 0 && who.Length > 0)
                    {
                        var sentto = textBox1.Text.Remove(10).Trim();
                        if (sentto.Length > 0)
                        {
                            socket.Sent(qq.SentMessage(sentto, msg));
                            textBlockr.Text += "" + NowTime() + "" + who + " 说:" + msg + System.Environment.NewLine;
                            textBlocks.Text = "";
                        }
                    }
                }
                isShift = false;
            }
        }
    }
}
复制代码

  在这个版本的协议里面,协议都是通过明文发送的,可以直接通过拦截数据包去得到真实的消息信息,具体的做法是,下载一个Kjava10一下的手机QQ,然后装一个java模拟器,再然后找一个拦截网络包的工具,剩下的,你知道的……

  以上就只这个手机QQ的全部实现了,其实有用的只有协议的部分,其他的代码都只是这样实现能成功的参考,完全当作垃圾也行……

  9.18,钓鱼岛是中国的!!!

                                                                                                      迹

                                                                                                    2012 09 18

 
 
原文地址:https://www.cnblogs.com/Leo_wl/p/2980956.html