P2P之UDP穿透NAT的原理与C#实现

2020年02月02日 阅读数:48
这篇文章主要向大家介绍P2P之UDP穿透NAT的原理与C#实现,主要内容包括基础应用、实用技巧、原理机制等方面,希望对大家有所帮助。

P2PUDP穿透NAT的原理与实现

声明:原文来自P2P中国网,C#实现是本人作的,供参考 安全

关键字:P2P, UDP, NAT, .NET 服务器

 

论坛上常常有对P2P原理的讨论,可是讨论归讨论,不多有实质的东西产生(源代码)。呵呵,在这里我就用本身实现的一个源代码来讲明UDP穿越NAT的原理。网络

首先先介绍一些基本概念:函数

    NAT(Network Address Translators),网络地址转换:网络地址转换是在IP地址日益缺少的状况下产生的,它的主要目的就是为了可以地址重用。NAT分为两大类,基本的NATNAPT(Network Address/Port Translator)oop

    最开始NAT是运行在路由器上的一个功能模块。测试

    最早提出的是基本的NAT,它的产生基于以下事实:一个私有网络(域)中的节点中只有不多的节点须要与外网链接(呵呵,这是在上世纪90年代中期提出的)。那么这个子网中其实只有少数的节点须要全球惟一的IP地址,其余的节点的IP地址应该是能够重用的。this

    所以,基本的NAT实现的功能很简单,在子网内使用一个保留的IP子网段,这些IP对外是不可见的。子网内只有少数一些IP地址能够对应到真正全球惟一的IP地址。若是这些节点须要访问外部网络,那么基本NAT就负责将这个节点的子网内IP转化为一个全球惟一的IP而后发送出去。(基本的NAT会改变IP包中的原IP地址,可是不会改变IP包中的端口)spa

    关于基本的NAT能够参看RFC 1631.net

另一种NAT叫作NAPT,从名称上咱们也能够看得出,NAPT不但会改变通过这个NAT设备的IP数据报的IP地址,还会改变IP数据报的TCP/UDP端口。基本NAT的设备可能咱们见的很少(呵呵,我没有见到过),NAPT才是咱们真正讨论的主角。看下图:

线程

    有一个私有网络10.*.*.*Client A是其中的一台计算机,这个网络的网关(一个NAT设备)的外网IP155.99.25.11(应该还有一个内网的IP地址,好比10.0.0.10)。若是Client A中的某个进程(这个进程建立了一个UDP Socket,这个Socket绑定1234端口)想访问外网主机18.181.0.311235端口,那么当数据包经过NAT时会发生什么事情呢?

    首先NAT会改变这个数据包的原IP地址,改成155.99.25.11。接着NAT会为这个传输建立一个SessionSession是一个抽象的概念,若是是TCP,也许Session是由一个SYN包开始,以一个FIN包结束。而UDP呢,以这个IP的这个端口的第一个UDP开始,结束呢,呵呵,也许是几分钟,也许是几小时,这要看具体的实现了)而且给这个Session分配一个端口,好比62000,而后改变这个数据包的源端口为62000。因此原本是(10.0.0.1:1234->18.181.0.31:1235)的数据包到了互联网上变为了(155.99.25.11:62000->18.181.0.31:1235)。

一旦NAT建立了一个Session后,NAT会记住62000端口对应的是10.0.0.11234端口,之后从18.181.0.31发送到62000端口的数据会被NAT自动的转发到10.0.0.1上。(注意:这里是说18.181.0.31发送到62000端口的数据会被转发,其余的IP发送到这个端口的数据将被NAT抛弃)这样Client A就与Server S1创建以了一个链接。

呵呵,上面的基础知识可能不少人都知道了,那么下面是关键的部分了。

看看下面的状况:


  
接上面的例子,若是Client A的原来那个Socket(绑定了1234端口的那个UDP Socket)又接着向另一个Server S2发送了一个UDP包,那么这个UDP包在经过NAT时会怎么样呢?

    这时可能会有两种状况发生,一种是NAT再次建立一个Session,而且再次为这个Session分配一个端口号(好比:62001)。另一种是NAT再次建立一个Session,可是不会新分配一个端口号,而是用原来分配的端口号62000。前一种NAT叫作Symmetric NAT,后一种叫作Cone NAT。咱们指望咱们的NAT是第二种,呵呵,若是你的NAT恰好是第一种,那么极可能会有不少P2P软件失灵。(能够庆幸的是,如今绝大多数的NAT属于后者,即Cone NAT

    好了,咱们看到,经过NAT,子网内的计算机向外连结是很容易的(NAT至关于透明的,子网内的和外网的计算机不用知道NAT的状况)。

    可是若是外部的计算机想访问子网内的计算机就比较困难了(而这正是P2P所须要的)。

那么咱们若是想从外部发送一个数据报给内网的计算机有什么办法呢?首先,咱们必须在内网的NAT上打上一个“洞”(也就是前面咱们说的在NAT上创建一个Session),这个洞不能由外部来打,只能由内网内的主机来打。并且这个洞是有方向的,好比从内部某台主机(好比:192.168.0.10)向外部的某个IP(好比:219.237.60.1)发送一个UDP包,那么就在这个内网的NAT设备上打了一个方向为219.237.60.1的“洞”,(这就是称为UDP Hole Punching的技术)之后219.237.60.1就能够经过这个洞与内网的192.168.0.10联系了。(可是其余的IP不能利用这个洞)。

呵呵,如今该轮到咱们的正题P2P了。有了上面的理论,实现两个内网的主机通信就差最后一步了:那就是鸡生蛋仍是蛋生鸡的问题了,两边都没法主动发出链接请求,谁也不知道谁的公网地址,那咱们如何来打这个洞呢?咱们须要一个中间人来联系这两个内网主机。

如今咱们来看看一个P2P软件的流程,如下图为例:


   
首先,Client A登陆服务器,NAT A为此次的Session分配了一个端口60000,那么Server S收到的Client A的地址是202.187.45.3:60000,这就是Client A的外网地址了。一样,Client B登陆Server SNAT B给这次Session分配的端口是40000,那么Server S收到的B的地址是187.34.1.56:40000

    此时,Client AClient B均可以与Server S通讯了。若是Client A此时想直接发送信息给Client B,那么他能够从Server S那儿得到B的公网地址187.34.1.56:40000,是否是Client A向这个地址发送信息Client B就能收到了呢?答案是不行,由于若是这样发送信息,NAT B会将这个信息丢弃(由于这样的信息是不请自来的,为了安全,大多数NAT都会执行丢弃动做)。如今咱们须要的是在NAT B上打一个方向为202.187.45.3(即Client A的外网地址)的洞,那么Client A发送到187.34.1.56:40000的信息,Client B就能收到了。这个打洞命令由谁来发呢,呵呵,固然是Server S

    总结一下这个过程:若是Client A想向Client B发送信息,那么Client A发送命令给Server S,请求Server S命令Client BClient A方向打洞。呵呵,是否是很绕口,不过不要紧,想想就很清楚了,况且还有源代码呢(侯老师说过:在源代码面前没有秘密 8)),而后Client A就能够经过Client B的外网地址与Client B通讯了。

    注意:以上过程只适合于Cone NAT的状况,若是是Symmetric NAT,那么当Client BClient A打洞的端口已经从新分配了,Client B将没法知道这个端口(若是Symmetric NAT的端口是顺序分配的,那么咱们或许能够猜想这个端口号,但是因为可能致使失败的因素太多,咱们不推荐这种猜想端口的方法)。   

    下面是一个模拟P2P聊天的过程的源代码,过程很简单,P2PServer运行在一个拥有公网IP的计算机上,P2PClient运行在两个不一样的NAT后(注意,若是两个客户端运行在一个NAT后,本程序极可能不能运行正常,这取决于你的NAT是否支持loopback translation,详见http://midcom-p2p.sourceforge.net/draft-ford-midcom-p2p-01.txt,固然,此问题能够经过双方先尝试链接对方的内网IP来解决,可是这个代码只是为了验证原理,并无处理这些问题),后登陆的计算机能够得到先登陆计算机的用户名,后登陆的计算机经过send username message的格式来发送消息。若是发送成功,说明你已取得了直接与对方链接的成功。

    程序如今支持三个命令:send , getu , exit

   

    send格式:send username message

    功能:发送信息给username

   

    getu格式:getu

    功能:得到当前服务器用户列表

   

    exit格式:exit

功能:注销与服务器的链接(服务器不会自动监测客户是否吊线)

 

源代码

注:原文代码是用C++写的,这里仅附上C#代码

1.  WellKnown公用库

namespace P2P.WellKnown

{

    using System;

    using System.IO;

using System.Runtime.Serialization.Formatters.Binary;

    /// <summary>

    /// P2PConsts 的摘要说明。

    /// </summary>

    public class P2PConsts

    {

        /// <summary>

        /// 服务器侦听端口号

        /// </summary>

public const int SRV_PORT  = 2280;

    }

        /// <summary>

    /// User 的摘要说明。

    /// </summary>

    [Serializable]

    public class User

    {

        protected string userName;

        protected IPEndPoint netPoint;

 

        public User(string UserName, IPEndPoint NetPoint)

        {

            this.userName = userName;

            this.netPoint = NetPoint;

        }

        public string UserName

        {

            get { return userName; }

        }

 

        public IPEndPoint NetPoint

        {

            get { return netPoint; }

            set { netPoint = value;}

        }

    }

    /// <summary>

    /// UserCollection 的摘要说明。

    /// </summary>

    [Serializable]

    public class UserCollection : CollectionBase

    {

        public void Add(User user)

        {

            InnerList.Add(user);

        }

 

        public void Remove(User user)

        {

            InnerList.Remove(user);

        }

 

        public User this[int index]

        {

            get { return (User)InnerList[index]; }

        }

 

        public User Find(string userName)

        {

            foreach(User user in this)

            {

                if (string.Compare(userName, user.UserName, true) == 0)

                {

                    return user;

                }

            }

            return null;

        }

    }

    /// <summary>

    /// FormatterHelper 序列化,反序列化消息的帮助类

    /// </summary>

    public class FormatterHelper

    {

        public static byte[] Serialize(object obj)

        {

            BinaryFormatter binaryF = new BinaryFormatter();

            MemoryStream ms = new MemoryStream(1024*10);

            binaryF.Serialize(ms, obj);

            ms.Seek(0, SeekOrigin.Begin);

            byte[] buffer = new byte[(int)ms.Length];

            ms.Read(buffer, 0, buffer.Length);

            ms.Close();

            return buffer;

        }

 

        public static object Deserialize(byte[] buffer)

        {

            BinaryFormatter binaryF = new BinaryFormatter();

            MemoryStream ms = new MemoryStream(buffer, 0, buffer.Length, false);

            object obj = binaryF.Deserialize(ms);

            ms.Close();

            return obj;

        }

    }

    /// <summary>

    /// Message base class

    /// </summary>

    [System.Serializable]

    public abstract class MessageBase

    {

    }

 

    // Message from Client to Server

    namespace C2S

    {

        /// <summary>

        /// 客户端发送到服务器的消息基类

        /// </summary>

        public abstract class CSMessage : MessageBase

        {

            private string userName;

            protected CSMessage(string anUserName)

            {

                userName = anUserName;

            }

            public string UserName

            {

                get { return userName; }

            }

        }

        /// <summary>

        /// 用户登陆消息

        /// </summary>

        public class LoginMessage : CSMessage

        {

            private string password;

            public LoginMessage(string userName, string password) : base(userName)

            {

                this.password = password;

            }

            public string Password

            {

                get { return password; }

            }

        }

        /// <summary>

        /// 用户登出消息

        /// </summary>

        public class LogoutMessage : CSMessage

        {

            public LogoutMessage(string userName) : base(userName)

            {}

        }

        /// <summary>

        /// 请求用户列表消息

        /// </summary>

        public class GetUsersMessage : CSMessage

        {

            public GetUsersMessage(string userName) : base(userName)

            {}

        }

        /// <summary>

        /// 请求Purch Hole消息

        /// </summary>

        public class TranslateMessage : CSMessage

        {

            protected string toUserName;

            public TranslateMessage(string userName, string toUserName) : base(userName)

            {

                this.toUserName = toUserName;

            }

            public string ToUserName

            {

                get { return this.toUserName; }

            }

        }

    }

 

    // Message from server to the client

    namespace S2C

    {

        /// <summary>

        /// 服务器发送到客户端消息基类

        /// </summary>

        public abstract class SCMessage : MessageBase

        {}

        /// <summary>

        /// 请求用户列表应答消息

        /// </summary>

        public class GetUsersResponseMessage : SCMessage

        {

            private UserCollection userList;

            public GetUsersResponseMessage(UserCollection users)

            {

                this.userList = users;

            }

            public UserCollection UserList

            {

                get { return userList; }

            }

        }

        /// <summary>

        /// 转发请求Purch Hole消息

        /// </summary>

        public class SomeOneCallYouMessage : SCMessage

        {

            protected System.Net.IPEndPoint remotePoint;

            public SomeOneCallYouMessage(System.Net.IPEndPoint point)

            {

                this.remotePoint = point;

            }

            public System.Net.IPEndPoint RemotePoint

            {

                get { return remotePoint; }

            }

        }

    }

 

    // Message from peer to the peer

    namespace P2P

    {

        /// <summary>

        /// 点对点消息基类

        /// </summary>

        public abstract class PPMessage : MessageBase

        {}

        /// <summary>

        /// 测试消息

        /// </summary>

        public class WorkMessage : PPMessage

        {

            private string message;

            public WorkMessage(string msg)

            {

                message = msg;

            }

            public string Message

            {

                get { return message; }

            }

        }

        /// <summary>

        /// 测试应答消息

        /// </summary>

        public class ACKMessage : PPMessage

        {

        }

        /// <summary>

        /// P2P Purch Hole Message

        /// </summary>

        public class TrashMessage : PPMessage

        {}

    }  

}

 

 

2.  P2Pserver

namespace P2P.P2PServer

{

    using System;

    using System.Net;

    using System.Net.Sockets;

    using System.Threading;

    using P2P.WellKnown;

    /// <summary>

    /// AppClass 的摘要说明。

    /// </summary>

    public class AppClass

    {

        public static void Main()

        {

            Server server = new Server();

            try

            {

                server.Start();

                Console.ReadLine();

                server.Stop();

            }

            catch

            {

            }

        }

    }

    /// <summary>

    /// Server 的摘要说明。

    /// </summary>

    public class Server

    {

        private UdpClient server;

        private UserCollection userList;

        private Thread serverThread;

        private IPEndPoint remotePoint;

 

        public Server()

        {

            userList = new UserCollection();

            remotePoint = new IPEndPoint(IPAddress.Any, 0);

            serverThread = new Thread(new ThreadStart(Run));

        }

 

        public void Start()

        {

            try

            {

                server = new UdpClient(P2PConsts.SRV_PORT);

                serverThread.Start();

                Console.WriteLine("P2P Server started, waiting client connect...");

            }

            catch(Exception exp)

            {

                Console.WriteLine("Start P2P Server error: " + exp.Message);

                throw exp;

            }

        }

 

        public void Stop()

        {

            Console.WriteLine("P2P Server stopping...");

            try

            {

                serverThread.Abort();

                server.Close();

                Console.WriteLine("Stop OK.");

            }

            catch(Exception exp)

            {

                Console.WriteLine("Stop error: " + exp.Message);

                throw exp;

            }

 

        }

 

        private void Run()

        {

            byte[] buffer = null;

            while (true)

            {

                byte[] msgBuffer = server.Receive(ref remotePoint);

                try

                {

                    object msgObj = FormatterHelper.Deserialize(msgBuffer);

                    Type msgType = msgObj.GetType();

                    if (msgType == typeof(P2P.WellKnown.C2S.LoginMessage))

                    {

                        // 转换接受的消息

                        P2P.WellKnown.C2S.LoginMessage lginMsg = (P2P.WellKnown.C2S.LoginMessage)msgObj;

                        Console.WriteLine("has an user login: {0}", lginMsg.UserName);

                        // 添加用户到列表

                        IPEndPoint userEndPoint = new IPEndPoint(remotePoint.Address, remotePoint.Port);

                        User user = new User(lginMsg.UserName, userEndPoint);

                        userList.Add(user);

                        // 发送应答消息

                        P2P.WellKnown.S2C.GetUsersResponseMessage usersMsg = new P2P.WellKnown.S2C.GetUsersResponseMessage(userList);

                        buffer = FormatterHelper.Serialize(usersMsg);

                        server.Send(buffer, buffer.Length, remotePoint);

                    }

                    else if (msgType == typeof(P2P.WellKnown.C2S.LogoutMessage))

                    {

                        // 转换接受的消息

                        P2P.WellKnown.C2S.LogoutMessage lgoutMsg = (P2P.WellKnown.C2S.LogoutMessage)msgObj;

                        Console.WriteLine("has an user logout: {0}", lgoutMsg.UserName);

                        // 从列表中删除用户

                        User lgoutUser = userList.Find(lgoutMsg.UserName);

                        if (lgoutUser != null)

                        {

                            userList.Remove(lgoutUser);

                        }

                    }

                    else if (msgType == typeof(P2P.WellKnown.C2S.TranslateMessage))

                    {

                        // 转换接受的消息

                        P2P.WellKnown.C2S.TranslateMessage transMsg = (P2P.WellKnown.C2S.TranslateMessage)msgObj;

                        Console.WriteLine("{0}(1) wants to p2p {2}", remotePoint.Address.ToString(), transMsg.UserName, transMsg.ToUserName);

                        // 获取目标用户

                        User toUser = userList.Find(transMsg.ToUserName);

                        // 转发Purch Hole请求消息

                        if (toUser == null)

                        {

                            Console.WriteLine("Remote host {0} cannot be found at index server", transMsg.ToUserName);                          

                        }

                        else

                        {

                            P2P.WellKnown.S2C.SomeOneCallYouMessage transMsg2 = new P2P.WellKnown.S2C.SomeOneCallYouMessage(remotePoint);

                            buffer = FormatterHelper.Serialize(transMsg);

                            server.Send(buffer, buffer.Length, toUser.NetPoint);                           

                        }

                    }

                    else if (msgType == typeof(P2P.WellKnown.C2S.GetUsersMessage))

                    {

                        // 发送当前用户信息到全部登陆客户

                        P2P.WellKnown.S2C.GetUsersResponseMessage srvResMsg = new P2P.WellKnown.S2C.GetUsersResponseMessage(userList);                       

                        buffer = FormatterHelper.Serialize(srvResMsg);

                        foreach(User user in userList)

                        {

                            server.Send(buffer, buffer.Length, user.NetPoint);

                        }

                    }

                    Thread.Sleep(500);

                }

                catch{}

            }

        }

    }

}

 

 

3.  P2Pclient

namespace P2P.P2PClient

{

    using System;

    using System.Net;

    using System.Net.Sockets;

    using System.Threading;

    using P2P.WellKnown;

    /// <summary>

    /// AppClass 的摘要说明。

    /// </summary>

    public class AppClass

    {

        public static void Main()

        {

            Client client = new Client("202.96.134.103");

            client.ConnectToServer("myname", "mypassword");

            client.Start();

            Console.WriteLine("test arguments");

            while (true)

            {

                string str = Console.ReadLine();

                client.PaserCommand(str);

            }

        }

    }

    /// <summary>

    /// Client 的摘要说明。

    /// </summary>

    public class Client : IDisposable

    {

        private const int MAXRETRY = 10;

        private UdpClient client;

        private IPEndPoint hostPoint;

        private IPEndPoint remotePoint;

        private UserCollection userList;

        private string myName;

        private bool ReceivedACK;

        private Thread listenThread;

 

        public Client(string serverIP)

        {

            ReceivedACK = false;

            remotePoint = new IPEndPoint(IPAddress.Any, 0);

            hostPoint = new IPEndPoint(IPAddress.Parse(serverIP), P2PConsts.SRV_PORT);

            client = new UdpClient();

            userList = new UserCollection();

            listenThread = new Thread(new ThreadStart(Run));

        }

 

        public void Start()

        {

            if (this.listenThread.ThreadState==ThreadState.Unstarted)

            {

                this.listenThread.Start();

                Console.WriteLine("You can input you command:/n");

                Console.WriteLine("Command Type:/"send/",/"exit/",/"getu/"");

                Console.WriteLine("Example : send Username Message");

                Console.WriteLine("          exit");

                Console.WriteLine("          getu");

            }

        }

 

        public void ConnectToServer(string userName, string password)

        {

            myName = userName;

            // 发送登陆消息到服务器

            P2P.WellKnown.C2S.LoginMessage lginMsg = new P2P.WellKnown.C2S.LoginMessage(userName, password);

            byte[] buffer = FormatterHelper.Serialize(lginMsg);

            client.Send(buffer, buffer.Length, hostPoint);

            // 接受服务器的登陆应答消息

            buffer = client.Receive(ref remotePoint);

            P2P.WellKnown.S2C.GetUsersResponseMessage srvResMsg = (P2P.WellKnown.S2C.GetUsersResponseMessage)FormatterHelper.Deserialize(buffer);

            // 更新用户列表

            userList.Clear();

            foreach(User user in srvResMsg.UserList)

            {

                userList.Add(user);

            }

            this.DisplayUsers(userList);

        }

 

        /// <summary>

        /// 这是主要的函数:发送一个消息给某个用户(C)

        /// 流程:直接向某个用户的外网IP发送消息,若是此前没有联系过

        /// 那么此消息将没法发送,发送端等待超时。

        /// 超时后,发送端将发送一个请求信息到服务端,要求服务端发送

        /// 给客户C一个请求,请求C给本机发送打洞消息

        /// *以上流程将重复MAXRETRY次

        /// </summary>

        /// <param name="toUserName">对方用户名</param>

        /// <param name="message">待发送的消息</param>

        /// <returns></returns>

        private bool SendMessageTo(string toUserName, string message)

        {

            User toUser = userList.Find(toUserName);

            if (toUser == null)

            {

                return false;

            }

            for (int i=0; i<MAXRETRY; i++)

            {

                P2P.WellKnown.P2P.WorkMessage workMsg = new P2P.WellKnown.P2P.WorkMessage(message);

                byte[] buffer = FormatterHelper.Serialize(workMsg);

                client.Send(buffer, buffer.Length, toUser.NetPoint);

               

                // 等待接收线程将标记修改

                for (int j=0; j<10; j++)

                {

                    if (this.ReceivedACK)

                    {

                        this.ReceivedACK = false;

                        return true;

                    }

                    else

                    {

                        Thread.Sleep(300);

                    }

                }

                // 没有接收到目标主机的回应,认为目标主机的端口映射没有

                // 打开,那么发送请求信息给服务器,要服务器告诉目标主机

                // 打开映射端口(UDP打洞)

                P2P.WellKnown.C2S.TranslateMessage transMsg = new P2P.WellKnown.C2S.TranslateMessage(myName, toUserName);

                buffer = FormatterHelper.Serialize(transMsg);

                client.Send(buffer, buffer.Length, hostPoint);

                // 等待对方先发送信息

                Thread.Sleep(100);

            }

            return false;

        }

 

        public void PaserCommand(string cmdstring)

        {

            cmdstring = cmdstring.Trim();

            string[] args = cmdstring.Split(new char[]{' '});

            if (args.Length > 0)

            {

                if (string.Compare(args[0], "exit", true) == 0)

                {

                    P2P.WellKnown.C2S.LogoutMessage lgoutMsg = new P2P.WellKnown.C2S.LogoutMessage(myName);

                    byte[] buffer = FormatterHelper.Serialize(lgoutMsg);

                    client.Send(buffer, buffer.Length, hostPoint);

                    // do clear something here

                    Dispose();

                    System.Environment.Exit(0);

                }

                else if (string.Compare(args[0], "send", true) == 0)

                {                  

                    if (args.Length > 2)

                    {

                        string toUserName = args[1];

                        string message    = "";

                        for(int i=2; i<args.Length; i++)

                        {

                            if (args[i] == "") message += " ";

                            else message += args[i];

                        }

                        if (this.SendMessageTo(toUserName, message))

                        {

                            Console.WriteLine("Send OK!");

                        }

                        else

                            Console.WriteLine("Send Failed!");

                    }

                }

                else if (string.Compare(args[0], "getu", true) == 0)

                {

                    P2P.WellKnown.C2S.GetUsersMessage getUserMsg = new P2P.WellKnown.C2S.GetUsersMessage(myName);

                    byte[] buffer = FormatterHelper.Serialize(getUserMsg);

                    client.Send(buffer, buffer.Length, hostPoint);

                }

                else

                {

                    Console.WriteLine("Unknown command {0}", cmdstring);

                }

            }

        }

 

        private void DisplayUsers(UserCollection users)

        {

            foreach (User user in users)

            {

                Console.WriteLine("Username: {0}, IP:{1}, Port:{2}", user.UserName, user.NetPoint.Address.ToString(), user.NetPoint.Port);

            }

        }

 

        private void Run()

        {

            byte[] buffer;

            while (true)

            {

                buffer = client.Receive(ref remotePoint);

                object msgObj = FormatterHelper.Deserialize(buffer);

                Type msgType = msgObj.GetType();

                if (msgType == typeof(P2P.WellKnown.S2C.GetUsersResponseMessage))

                {

                    // 转换消息

                    P2P.WellKnown.S2C.GetUsersResponseMessage usersMsg = (P2P.WellKnown.S2C.GetUsersResponseMessage)msgObj;

                    // 更新用户列表

                    userList.Clear();

                    foreach(User user in usersMsg.UserList)

                    {

                        userList.Add(user);

                    }

                    this.DisplayUsers(userList);

                }

                else if (msgType == typeof(P2P.WellKnown.S2C.SomeOneCallYouMessage))

                {

                    // 转换消息

                    P2P.WellKnown.S2C.SomeOneCallYouMessage purchReqMsg = (P2P.WellKnown.S2C.SomeOneCallYouMessage)msgObj;

                    // 发送打洞消息到远程主机

                    P2P.WellKnown.P2P.TrashMessage trashMsg = new P2P.WellKnown.P2P.TrashMessage();

                    buffer = FormatterHelper.Serialize(trashMsg);

                    client.Send(buffer, buffer.Length, purchReqMsg.RemotePoint);

                }

                else if (msgType == typeof(P2P.WellKnown.P2P.WorkMessage))

                {

                    // 转换消息

                    P2P.WellKnown.P2P.WorkMessage workMsg = (P2P.WellKnown.P2P.WorkMessage)msgObj;

                    Console.WriteLine("Receive a message: {0}", workMsg.Message);

                    // 发送应答消息

                    P2P.WellKnown.P2P.ACKMessage ackMsg = new P2P.WellKnown.P2P.ACKMessage();

                    buffer = FormatterHelper.Serialize(ackMsg);

                    client.Send(buffer, buffer.Length, remotePoint);

                }

                else if (msgType == typeof(P2P.WellKnown.P2P.ACKMessage))

                {

                    this.ReceivedACK = true;

                }

                else if (msgType == typeof(P2P.WellKnown.P2P.TrashMessage))

                {

                    Console.WriteLine("Recieve a trash message");

                }

                Thread.Sleep(100);

            }

        }

        #region IDisposable 成员

 

        public void Dispose()

        {

            try

            {

                this.listenThread.Abort();

                this.client.Close();

            }

            catch

            {}

        }

 

        #endregion

    }

}

上一篇: Menu菜单(一)