P2P之UDP穿透NAT的原理与实现
P2P之UDP穿透NAT的原理与实现
声明:原文来自P2P中国网,C#实现是也是转载别人的,供参考
再次声明,转载过来的时候没有经过我的亲自测试,代码编译和运行可能会碰到问题,请擅于发现和解决问题。我们学习的思想方法,不是复制过来编译一下,就打上了自己的标记。尊重原作者的劳动成果,转载请注明原出处。
论坛上经常有对P2P原理的讨论,但是讨论归讨论,很少有实质的东西产生(源代码)。呵呵,在这里我就用自己实现的一个源代码来说明UDP穿越NAT的原理。
首先先介绍一些基本概念:
NAT(Network Address Translators),网络地址转换:网络地址转换是在IP地址日益缺乏的情况下产生的,它的主要目的就是为了能够地址重用。NAT分为两大类,基本的NAT和NAPT(Network Address/Port Translator)。
最开始NAT是运行在路由器上的一个功能模块。
最先提出的是基本的NAT,它的产生基于如下事实:一个私有网络(域)中的节点中只有很少的节点需要与外网连接(呵呵,这是在上世纪90年代中期提出的)。那么这个子网中其实只有少数的节点需要全球唯一的IP地址,其他的节点的IP地址应该是可以重用的。
因此,基本的NAT实现的功能很简单,在子网内使用一个保留的IP子网段,这些IP对外是不可见的。子网内只有少数一些IP地址可以对应到真正全球唯一的 IP地址。如果这些节点需要访问外部网络,那么基本NAT就负责将这个节点的子网内IP转化为一个全球唯一的IP然后发送出去。(基本的NAT会改变IP 包中的原IP地址,但是不会改变IP包中的端口)
关于基本的NAT可以参看RFC 1631
另外一种NAT叫做NAPT,从名称上我们也可以看得出,NAPT不但会改变经过这个NAT设备的IP数据报的IP地址,还会改变IP数据报的TCP/UDP端口。基本NAT的设备可能我们见的不多(呵呵,我没有见到过),NAPT才是我们真正讨论的主角。看下图:
                                                                         Server S1                         
                                                            18.181.0.31:1235                          
                                                                           |
                                  ^  Session 1 (A-S1)  ^      |  
                                   |  18.181.0.31:1235  |      |   
                                  v 155.99.25.11:62000 v   |    
                                                                          |
                                                                      NAT
                                                                155.99.25.11
                                                                          |
                                  ^  Session 1 (A-S1)  ^      |  
                                   |  18.181.0.31:1235  |      |  
                                    v   10.0.0.1:1234    v      |  
                                                                          |
                                                                    Client A
                                                              10.0.0.1:1234
    有一个私有网络10.*.*.*,Client A是其中的一台计算机,这个网络的网关(一个NAT设备)的外网IP是155.99.25.11(应该还有一个内网的IP地址,比如 10.0.0.10)。如果Client A中的某个进程(这个进程创建了一个UDP Socket,这个Socket绑定1234端口)想访问外网主机18.181.0.31的1235端口,那么当数据包通过NAT时会发生什么事情呢?
首先NAT会改变这个数据包的原IP地址,改为155.99.25.11。接着NAT会为这个传输创建一个Session(Session是一个抽象的概念,如果是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.1的1234端口,以后从18.181.0.31发送到62000端口的数据会被NAT自动的转发到 10.0.0.1上。(注意:这里是说18.181.0.31发送到62000端口的数据会被转发,其他的IP发送到这个端口的数据将被NAT抛弃)这样 Client A就与Server S1建立以了一个连接。
呵呵,上面的基础知识可能很多人都知道了,那么下面是关键的部分了。
看看下面的情况:
Server S1                                     Server S2
 18.181.0.31:1235                              138.76.29.7:1235
        |                                             |
        |                                             |
        +----------------------+----------------------+
                               |
   ^  Session 1 (A-S1)  ^      |      ^  Session 2 (A-S2)  ^
   |  18.181.0.31:1235  |      |      |  138.76.29.7:1235  |
   v 155.99.25.11:62000 v      |      v 155.99.25.11:62000 v
                               |
                            Cone NAT
                          155.99.25.11
                               |
   ^  Session 1 (A-S1)  ^      |      ^  Session 2 (A-S2)  ^
   |  18.181.0.31:1235  |      |      |  138.76.29.7:1235  |
   v   10.0.0.1:1234    v      |      v   10.0.0.1:1234    v
                               |
                            Client A
                         10.0.0.1:1234
接上面的例子,如果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软件的流程,以下图为例:
 Server S (219.237.60.1)
                          |
                          |
   +----------------------+----------------------+
   |                                             |
 NAT A (外网IP:202.187.45.3)                 NAT B (外网IP:187.34.1.56)
   |   (内网IP:192.168.0.1)                      | (内网IP:192.168.0.1)
   |                                             |
Client A  (192.168.0.20:4000)             Client B (192.168.0.10:40000)
首先,Client A登录服务器,NAT A为这次的Session分配了一个端口60000,那么Server S收到的Client A的地址是202.187.45.3:60000,这就是Client A的外网地址了。同样,Client B登录Server S,NAT B给此次Session分配的端口是40000,那么Server S收到的B的地址是187.34.1.56:40000。
此时,Client A与Client 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 B向Client A方向打洞。呵呵,是不是很绕口,不过没关系,想一想就很清楚了,何况还有源代码呢(侯老师说过:在源代码面前没有秘密 8)),然后Client A就可以通过Client B的外网地址与Client B通信了。
注意:以上过程只适合于Cone NAT的情况,如果是Symmetric NAT,那么当Client B向Client 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
namespace P2P.WellKnown2

3
 {
{4

5
 using System;
    using System;6

7
 using System.IO;
    using System.IO;8

9
 using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Binary;10

11
 /// <summary>
    /// <summary>12

13
 /// P2PConsts 的摘要说明。
    /// P2PConsts 的摘要说明。14

15
 /// </summary>
    /// </summary> 16

17
 public class P2PConsts
    public class P2PConsts18

19
 {
    {20

21
 /// <summary>
        /// <summary>22

23
 /// 服务器侦听端口号
        /// 服务器侦听端口号24

25
 /// </summary>
        /// </summary> 26

27
 public const int SRV_PORT  = 2280;
public const int SRV_PORT  = 2280;28

29
 }
    }30

31
 /// <summary>
        /// <summary>32

33
 /// User 的摘要说明。
    /// User 的摘要说明。34

35
 /// </summary>
    /// </summary> 36

37
 [Serializable]
    [Serializable]38

39
 public class User
    public class User40

41
 {
    {42

43
 protected string userName;
        protected string userName;44

45
 protected IPEndPoint netPoint;
        protected IPEndPoint netPoint;46

47
 
 48

49
 public User(string UserName, IPEndPoint NetPoint)
        public User(string UserName, IPEndPoint NetPoint)50

51
 {
        {52

53
 this.userName = userName;
            this.userName = userName;54

55
 this.netPoint = NetPoint;
            this.netPoint = NetPoint;56

57
 }
        }58

59
 public string UserName
        public string UserName60

61
 {
        {62

63
 get { return userName; }
            get { return userName; }64

65
 }
        }66

67
 
 68

69
 public IPEndPoint NetPoint
        public IPEndPoint NetPoint70

71
 {
        {72

73
 get { return netPoint; }
            get { return netPoint; }74

75
 set { netPoint = value;}
            set { netPoint = value;}76

77
 }
        }78

79
 }
    }80

81
 /// <summary>
    /// <summary>82

83
 /// UserCollection 的摘要说明。
    /// UserCollection 的摘要说明。84

85
 /// </summary>
    /// </summary> 86

87
 [Serializable]
    [Serializable]88

89
 public class UserCollection : CollectionBase
    public class UserCollection : CollectionBase90

91
 {
    {92

93
 public void Add(User user)
        public void Add(User user)94

95
 {
        {96

97
 InnerList.Add(user);
            InnerList.Add(user);98

99
 }
        }100

101
 
 102

103
 public void Remove(User user)
        public void Remove(User user)104

105
 {
        {106

107
 InnerList.Remove(user);
            InnerList.Remove(user);108

109
 }
        }110

111
 
 112

113
 public User this[int index]
        public User this[int index]114

115
 {
        {116

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

119
 }
        }120

121
 
 122

123
 public User Find(string userName)
        public User Find(string userName)124

125
 {
        {126

127
 foreach(User user in this)
            foreach(User user in this)128

129
 {
            {130

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

133
 {
                {134

135
 return user;
                    return user;136

137
 }
                }138

139
 }
            }140

141
 return null;
            return null;142

143
 }
        }144

145
 }
    }146

147
 /// <summary>
    /// <summary>148

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

151
 /// </summary>
    /// </summary> 152

153
 public class FormatterHelper
    public class FormatterHelper154

155
 {
    {156

157
 public static byte[] Serialize(object obj)
        public static byte[] Serialize(object obj)158

159
 {
        {160

161
 BinaryFormatter binaryF = new BinaryFormatter();
            BinaryFormatter binaryF = new BinaryFormatter();162

163
 MemoryStream ms = new MemoryStream(1024*10);
            MemoryStream ms = new MemoryStream(1024*10);164

165
 binaryF.Serialize(ms, obj);
            binaryF.Serialize(ms, obj);166

167
 ms.Seek(0, SeekOrigin.Begin);
            ms.Seek(0, SeekOrigin.Begin);168

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

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

173
 ms.Close();
            ms.Close();174

175
 return buffer;
            return buffer;176

177
 }
        }178

179
 
 180

181
 public static object Deserialize(byte[] buffer)
        public static object Deserialize(byte[] buffer)182

183
 {
        {184

185
 BinaryFormatter binaryF = new BinaryFormatter();
            BinaryFormatter binaryF = new BinaryFormatter();186

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

189
 object obj = binaryF.Deserialize(ms);
            object obj = binaryF.Deserialize(ms);190

191
 ms.Close();
            ms.Close();192

193
 return obj;
            return obj;194

195
 }
        }196

197
 }
    }198

199
 /// <summary>
    /// <summary>200

201
 /// Message base class
    /// Message base class202

203
 /// </summary>
    /// </summary>204

205
 [System.Serializable]
    [System.Serializable]206

207
 public abstract class MessageBase
    public abstract class MessageBase208

209
 {
    {210

211
 }
    }212

213
 
 214

215
 // Message from Client to Server
    // Message from Client to Server216

217
 namespace C2S
    namespace C2S218

219
 {
    {220

221
 /// <summary>
        /// <summary>222

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

225
 /// </summary>
        /// </summary>226

227
 public abstract class CSMessage : MessageBase
        public abstract class CSMessage : MessageBase228

229
 {
        {230

231
 private string userName;
            private string userName;232

233
 protected CSMessage(string anUserName)
            protected CSMessage(string anUserName)234

235
 {
            {236

237
 userName = anUserName;
                userName = anUserName;238

239
 }
            }240

241
 public string UserName
            public string UserName242

243
 {
            {244

245
 get { return userName; }
                get { return userName; }246

247
 }
            }248

249
 }
        }250

251
 /// <summary>
        /// <summary>252

253
 /// 用户登录消息
        /// 用户登录消息254

255
 /// </summary>
        /// </summary>256

257
 public class LoginMessage : CSMessage
        public class LoginMessage : CSMessage258

259
 {
        {260

261
 private string password;
            private string password;262

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

265
 {
            {266

267
 this.password = password;
                this.password = password;268

269
 }
            }270

271
 public string Password
            public string Password272

273
 {
            {274

275
 get { return password; }
                get { return password; }276

277
 }
            }278

279
 }
        }280

281
 /// <summary>
        /// <summary>282

283
 /// 用户登出消息
        /// 用户登出消息284

285
 /// </summary>
        /// </summary>286

287
 public class LogoutMessage : CSMessage
        public class LogoutMessage : CSMessage288

289
 {
        {290

291
 public LogoutMessage(string userName) : base(userName)
            public LogoutMessage(string userName) : base(userName)292

293
 {}
            {}294

295
 }
        }296

297
 /// <summary>
        /// <summary>298

299
 /// 请求用户列表消息
        /// 请求用户列表消息300

301
 /// </summary>
        /// </summary>302

303
 public class GetUsersMessage : CSMessage
        public class GetUsersMessage : CSMessage304

305
 {
        {306

307
 public GetUsersMessage(string userName) : base(userName)
            public GetUsersMessage(string userName) : base(userName)308

309
 {}
            {}310

311
 }
        }312

313
 /// <summary>
        /// <summary>314

315
 /// 请求Purch Hole消息
        /// 请求Purch Hole消息316

317
 /// </summary>
        /// </summary>318

319
 public class TranslateMessage : CSMessage
        public class TranslateMessage : CSMessage320

321
 {
        {322

323
 protected string toUserName;
            protected string toUserName;324

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

327
 {
            {328

329
 this.toUserName = toUserName;
                this.toUserName = toUserName;330

331
 }
            }332

333
 public string ToUserName
            public string ToUserName334

335
 {
            {336

337
 get { return this.toUserName; }
                get { return this.toUserName; }338

339
 }
            }340

341
 }
        }342

343
 }
    }344

345
 
 346

347
 // Message from server to the client
    // Message from server to the client348

349
 namespace S2C
    namespace S2C350

351
 {
    {352

353
 /// <summary>
        /// <summary>354

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

357
 /// </summary>
        /// </summary>358

359
 public abstract class SCMessage : MessageBase
        public abstract class SCMessage : MessageBase360

361
 {}
        {}362

363
 /// <summary>
        /// <summary>364

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

367
 /// </summary>
        /// </summary>368

369
 public class GetUsersResponseMessage : SCMessage
        public class GetUsersResponseMessage : SCMessage370

371
 {
        {372

373
 private UserCollection userList;
            private UserCollection userList;374

375
 public GetUsersResponseMessage(UserCollection users)
            public GetUsersResponseMessage(UserCollection users)376

377
 {
            {378

379
 this.userList = users;
                this.userList = users;380

381
 }
            }382

383
 public UserCollection UserList
            public UserCollection UserList384

385
 {
            {386

387
 get { return userList; }
                get { return userList; }388

389
 }
            }390

391
 }
        }392

393
 /// <summary>
        /// <summary>394

395
 /// 转发请求Purch Hole消息
        /// 转发请求Purch Hole消息396

397
 /// </summary>
        /// </summary>398

399
 public class SomeOneCallYouMessage : SCMessage
        public class SomeOneCallYouMessage : SCMessage400

401
 {
        {402

403
 protected System.Net.IPEndPoint remotePoint;
            protected System.Net.IPEndPoint remotePoint;404

405
 public SomeOneCallYouMessage(System.Net.IPEndPoint point)
            public SomeOneCallYouMessage(System.Net.IPEndPoint point)406

407
 {
            {408

409
 this.remotePoint = point;
                this.remotePoint = point;410

411
 }
            }412

413
 public System.Net.IPEndPoint RemotePoint
            public System.Net.IPEndPoint RemotePoint414

415
 {
            {416

417
 get { return remotePoint; }
                get { return remotePoint; }418

419
 }
            }420

421
 }
        }422

423
 }
    }424

425
 
 426

427
 // Message from peer to the peer
    // Message from peer to the peer428

429
 namespace P2P
    namespace P2P430

431
 {
    {432

433
 /// <summary>
        /// <summary>434

435
 /// 点对点消息基类
        /// 点对点消息基类436

437
 /// </summary>
        /// </summary>438

439
 public abstract class PPMessage : MessageBase
        public abstract class PPMessage : MessageBase440

441
 {}
        {}442

443
 /// <summary>
        /// <summary>444

445
 /// 测试消息
        /// 测试消息446

447
 /// </summary>
        /// </summary>448

449
 public class WorkMessage : PPMessage
        public class WorkMessage : PPMessage450

451
 {
        {452

453
 private string message;
            private string message;454

455
 public WorkMessage(string msg)
            public WorkMessage(string msg)456

457
 {
            {458

459
 message = msg;
                message = msg;460

461
 }
            }462

463
 public string Message
            public string Message464

465
 {
            {466

467
 get { return message; }
                get { return message; }468

469
 }
            }470

471
 }
        }472

473
 /// <summary>
        /// <summary>474

475
 /// 测试应答消息
        /// 测试应答消息476

477
 /// </summary>
        /// </summary>478

479
 public class ACKMessage : PPMessage
        public class ACKMessage : PPMessage480

481
 {
        {482

483
 }
        }484

485
 /// <summary>
        /// <summary>486

487
 /// P2P Purch Hole Message
        /// P2P Purch Hole Message488

489
 /// </summary>
        /// </summary>490

491
 public class TrashMessage : PPMessage
        public class TrashMessage : PPMessage492

493
 {}
        {}494

495
 }
    }  496

497
 }
}498

499
 
 500

2. P2Pserver

2

3
 namespace P2P.P2PServer
namespace P2P.P2PServer4

5
 {
{6

7
 using System;
    using System;8

9
 using System.Net;
    using System.Net;10

11
 using System.Net.Sockets;
    using System.Net.Sockets;12

13
 using System.Threading;
    using System.Threading;14

15
 using P2P.WellKnown;
    using P2P.WellKnown;16

17
 /// <summary>
    /// <summary>18

19
 /// AppClass 的摘要说明。
    /// AppClass 的摘要说明。20

21
 /// </summary>
    /// </summary>22

23
 public class AppClass
    public class AppClass24

25
 {
    {26

27
 public static void Main()
        public static void Main()28

29
 {
        {30

31
 Server server = new Server();
            Server server = new Server();32

33
 try
            try34

35
 {
            {36

37
 server.Start();
                server.Start();38

39
 Console.ReadLine();
                Console.ReadLine();40

41
 server.Stop();
                server.Stop();42

43
 }
            }44

45
 catch
            catch46

47
 {
            {48

49
 }
            }50

51
 }
        }52

53
 }
    }54

55
 /// <summary>
    /// <summary>56

57
 /// Server 的摘要说明。
    /// Server 的摘要说明。58

59
 /// </summary>
    /// </summary>60

61
 public class Server
    public class Server62

63
 {
    {64

65
 private UdpClient server;
        private UdpClient server;66

67
 private UserCollection userList;
        private UserCollection userList;68

69
 private Thread serverThread;
        private Thread serverThread;70

71
 private IPEndPoint remotePoint;
        private IPEndPoint remotePoint;72

73
 
 74

75
 public Server()
        public Server()76

77
 {
        {78

79
 userList = new UserCollection();
            userList = new UserCollection();80

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

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

85
 }
        }86

87
 
 88

89
 public void Start()
        public void Start()90

91
 {
        {92

93
 try
            try94

95
 {
            {96

97
 server = new UdpClient(P2PConsts.SRV_PORT);
                server = new UdpClient(P2PConsts.SRV_PORT);98

99
 serverThread.Start();
                serverThread.Start();100

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

103
 }
            }104

105
 catch(Exception exp)
            catch(Exception exp)106

107
 {
            {108

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

111
 throw exp;
                throw exp;112

113
 }
            }114

115
 }
        }116

117
 
 118

119
 public void Stop()
        public void Stop()120

121
 {
        {122

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

125
 try
            try126

127
 {
            {128

129
 serverThread.Abort();
                serverThread.Abort();130

131
 server.Close();
                server.Close();132

133
 Console.WriteLine("Stop OK.");
                Console.WriteLine("Stop OK.");134

135
 }
            }136

137
 catch(Exception exp)
            catch(Exception exp)138

139
 {
            {140

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

143
 throw exp;
                throw exp;144

145
 }
            }146

147
 
 148

149
 }
        }150

151
 
 152

153
 private void Run()
        private void Run()154

155
 {
        {156

157
 byte[] buffer = null;
            byte[] buffer = null;158

159
 while (true)
            while (true)160

161
 {
            {162

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

165
 try
                try166

167
 {
                {168

169
 object msgObj = FormatterHelper.Deserialize(msgBuffer);
                    object msgObj = FormatterHelper.Deserialize(msgBuffer);170

171
 Type msgType = msgObj.GetType();
                    Type msgType = msgObj.GetType();172

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

175
 {
                    {176

177
 // 转换接受的消息
                        // 转换接受的消息178

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

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

183
 // 添加用户到列表
                        // 添加用户到列表184

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

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

189
 userList.Add(user);
                        userList.Add(user);190

191
 // 发送应答消息
                        // 发送应答消息192

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

195
 buffer = FormatterHelper.Serialize(usersMsg);
                        buffer = FormatterHelper.Serialize(usersMsg);196

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

199
 }
                    }200

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

203
 {
                    {204

205
 // 转换接受的消息
                        // 转换接受的消息206

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

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

211
 // 从列表中删除用户
                        // 从列表中删除用户212

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

215
 if (lgoutUser != null)
                        if (lgoutUser != null)216

217
 {
                        {218

219
 userList.Remove(lgoutUser);
                            userList.Remove(lgoutUser);220

221
 }
                        }222

223
 }
                    }224

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

227
 {
                    {228

229
 // 转换接受的消息
                        // 转换接受的消息230

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

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

235
 // 获取目标用户
                        // 获取目标用户236

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

239
 // 转发Purch Hole请求消息
                        // 转发Purch Hole请求消息240

241
 if (toUser == null)
                        if (toUser == null)242

243
 {
                        {244

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

247
 }
                        }248

249
 else
                        else250

251
 {
                        {252

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

255
 buffer = FormatterHelper.Serialize(transMsg);
                            buffer = FormatterHelper.Serialize(transMsg);256

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

259
 }
                        }260

261
 }
                    }262

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

265
 {
                    {266

267
 // 发送当前用户信息到所有登录客户
                        // 发送当前用户信息到所有登录客户268

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

271
 buffer = FormatterHelper.Serialize(srvResMsg);
                        buffer = FormatterHelper.Serialize(srvResMsg);272

273
 foreach(User user in userList)
                        foreach(User user in userList)274

275
 {
                        {276

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

279
 }
                        }280

281
 }
                    }282

283
 Thread.Sleep(500);
                    Thread.Sleep(500);284

285
 }
                }286

287
 catch{}
                catch{}288

289
 }
            }290

291
 }
        }292

293
 }
    }294

295
 }
}296

3. P2Pclient
 namespace P2P.P2PClient
namespace P2P.P2PClient2

3
 {
{4

5
 using System;
    using System;6

7
 using System.Net;
    using System.Net;8

9
 using System.Net.Sockets;
    using System.Net.Sockets;10

11
 using System.Threading;
    using System.Threading;12

13
 using P2P.WellKnown;
    using P2P.WellKnown;14

15
 /// <summary>
    /// <summary>16

17
 /// AppClass 的摘要说明。
    /// AppClass 的摘要说明。18

19
 /// </summary>
    /// </summary>20

21
 public class AppClass
    public class AppClass22

23
 {
    {24

25
 public static void Main()
        public static void Main()26

27
 {
        {28

29
 Client client = new Client("202.96.134.103");
            Client client = new Client("202.96.134.103");30

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

33
 client.Start();
            client.Start();34

35
 Console.WriteLine("test arguments");
            Console.WriteLine("test arguments");36

37
 while (true)
            while (true)38

39
 {
            {40

41
 string str = Console.ReadLine();
                string str = Console.ReadLine();42

43
 client.PaserCommand(str);
                client.PaserCommand(str);44

45
 }
            }46

47
 }
        }48

49
 }
    }50

51
 /// <summary>
    /// <summary>52

53
 /// Client 的摘要说明。
    /// Client 的摘要说明。54

55
 /// </summary>
    /// </summary>56

57
 public class Client : IDisposable
    public class Client : IDisposable58

59
 {
    {60

61
 private const int MAXRETRY = 10;
        private const int MAXRETRY = 10;62

63
 private UdpClient client;
        private UdpClient client;64

65
 private IPEndPoint hostPoint;
        private IPEndPoint hostPoint;66

67
 private IPEndPoint remotePoint;
        private IPEndPoint remotePoint;68

69
 private UserCollection userList;
        private UserCollection userList;70

71
 private string myName;
        private string myName;72

73
 private bool ReceivedACK;
        private bool ReceivedACK;74

75
 private Thread listenThread;
        private Thread listenThread;76

77
 
 78

79
 public Client(string serverIP)
        public Client(string serverIP)80

81
 {
        {82

83
 ReceivedACK = false;
            ReceivedACK = false;84

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

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

89
 client = new UdpClient();
            client = new UdpClient();90

91
 userList = new UserCollection();
            userList = new UserCollection();92

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

95
 }
        }96

97
 
 98

99
 public void Start()
        public void Start()100

101
 {
        {102

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

105
 {
            {106

107
 this.listenThread.Start();
                this.listenThread.Start();108

109
 Console.WriteLine("You can input you command:\n");
                Console.WriteLine("You can input you command:\n");110

111
 Console.WriteLine("Command Type:\"send\",\"exit\",\"getu\"");
                Console.WriteLine("Command Type:\"send\",\"exit\",\"getu\"");112

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

115
 Console.WriteLine("          exit");
                Console.WriteLine("          exit");116

117
 Console.WriteLine("          getu");
                Console.WriteLine("          getu");118

119
 }
            }120

121
 }
        }122

123
 
 124

125
 public void ConnectToServer(string userName, string password)
        public void ConnectToServer(string userName, string password)126

127
 {
        {128

129
 myName = userName;
            myName = userName;130

131
 // 发送登录消息到服务器
            // 发送登录消息到服务器132

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

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

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

139
 // 接受服务器的登录应答消息
            // 接受服务器的登录应答消息140

141
 buffer = client.Receive(ref remotePoint);
            buffer = client.Receive(ref remotePoint);142

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

145
 // 更新用户列表
            // 更新用户列表146

147
 userList.Clear();
            userList.Clear();148

149
 foreach(User user in srvResMsg.UserList)
            foreach(User user in srvResMsg.UserList)150

151
 {
            {152

153
 userList.Add(user);
                userList.Add(user);154

155
 }
            }156

157
 this.DisplayUsers(userList);
            this.DisplayUsers(userList);158

159
 }
        }160

161
 
 162

163
 /// <summary>
        /// <summary>164

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

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

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

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

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

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

177
 /// </summary>
        /// </summary>178

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

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

183
 /// <returns></returns>
        /// <returns></returns>184

185
 private bool SendMessageTo(string toUserName, string message)
        private bool SendMessageTo(string toUserName, string message)186

187
 {
        {188

189
 User toUser = userList.Find(toUserName);
            User toUser = userList.Find(toUserName);190

191
 if (toUser == null)
            if (toUser == null)192

193
 {
            {194

195
 return false;
                return false;196

197
 }
            }198

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

201
 {
            {202

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

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

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

209
 
               210

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

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

215
 {
                {216

217
 if (this.ReceivedACK)
                    if (this.ReceivedACK)218

219
 {
                    {220

221
 this.ReceivedACK = false;
                        this.ReceivedACK = false;222

223
 return true;
                        return true;224

225
 }
                    }226

227
 else
                    else228

229
 {
                    {230

231
 Thread.Sleep(300);
                        Thread.Sleep(300);232

233
 }
                    }234

235
 }
                }236

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

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

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

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

245
 buffer = FormatterHelper.Serialize(transMsg);
                buffer = FormatterHelper.Serialize(transMsg);246

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

249
 // 等待对方先发送信息
                // 等待对方先发送信息250

251
 Thread.Sleep(100);
                Thread.Sleep(100);252

253
 }
            }254

255
 return false;
            return false;256

257
 }
        }258

259
 
 260

261
 public void PaserCommand(string cmdstring)
        public void PaserCommand(string cmdstring)262

263
 {
        {264

265
 cmdstring = cmdstring.Trim();
            cmdstring = cmdstring.Trim();266

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

269
 if (args.Length > 0)
            if (args.Length > 0)270

271
 {
            {272

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

275
 {
                {276

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

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

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

283
 // do clear something here
                    // do clear something here284

285
 Dispose();
                    Dispose();286

287
 System.Environment.Exit(0);
                    System.Environment.Exit(0);288

289
 }
                }290

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

293
 {
                {                  294

295
 if (args.Length > 2)
                    if (args.Length > 2)296

297
 {
                    {298

299
 string toUserName = args[1];
                        string toUserName = args[1];300

301
 string message    = "";
                        string message    = "";302

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

305
 {
                        {306

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

309
 else message += args[i];
                            else message += args[i];310

311
 }
                        }312

313
 if (this.SendMessageTo(toUserName, message))
                        if (this.SendMessageTo(toUserName, message))314

315
 {
                        {316

317
 Console.WriteLine("Send OK!");
                            Console.WriteLine("Send OK!");318

319
 }
                        }320

321
 else
                        else322

323
 Console.WriteLine("Send Failed!");
                            Console.WriteLine("Send Failed!");324

325
 }
                    }326

327
 }
                }328

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

331
 {
                {332

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

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

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

339
 }
                }340

341
 else
                else342

343
 {
                {344

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

347
 }
                }348

349
 }
            }350

351
 }
        }352

353
 
 354

355
 private void DisplayUsers(UserCollection users)
        private void DisplayUsers(UserCollection users)356

357
 {
        {358

359
 foreach (User user in users)
            foreach (User user in users)360

361
 {
            {362

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

365
 }
            }366

367
 }
        }368

369
 
 370

371
 private void Run()
        private void Run()372

373
 {
        {374

375
 byte[] buffer;
            byte[] buffer;376

377
 while (true)
            while (true)378

379
 {
            {380

381
 buffer = client.Receive(ref remotePoint);
                buffer = client.Receive(ref remotePoint);382

383
 object msgObj = FormatterHelper.Deserialize(buffer);
                object msgObj = FormatterHelper.Deserialize(buffer);384

385
 Type msgType = msgObj.GetType();
                Type msgType = msgObj.GetType();386

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

389
 {
                {390

391
 // 转换消息
                    // 转换消息392

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

395
 // 更新用户列表
                    // 更新用户列表396

397
 userList.Clear();
                    userList.Clear();398

399
 foreach(User user in usersMsg.UserList)
                    foreach(User user in usersMsg.UserList)400

401
 {
                    {402

403
 userList.Add(user);
                        userList.Add(user);404

405
 }
                    }406

407
 this.DisplayUsers(userList);
                    this.DisplayUsers(userList);408

409
 }
                }410

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

413
 {
                {414

415
 // 转换消息
                    // 转换消息416

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

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

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

423
 buffer = FormatterHelper.Serialize(trashMsg);
                    buffer = FormatterHelper.Serialize(trashMsg);424

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

427
 }
                }428

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

431
 {
                {432

433
 // 转换消息
                    // 转换消息434

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

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

439
 // 发送应答消息
                    // 发送应答消息440

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

443
 buffer = FormatterHelper.Serialize(ackMsg);
                    buffer = FormatterHelper.Serialize(ackMsg);444

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

447
 }
                }448

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

451
 {
                {452

453
 this.ReceivedACK = true;
                    this.ReceivedACK = true;454

455
 }
                }456

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

459
 {
                {460

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

463
 }
                }464

465
 Thread.Sleep(100);
                Thread.Sleep(100);466

467
 }
            }468

469
 }
        }470

471
 IDisposable 成员
        IDisposable 成员498

499
 }
    }500

501
 }
}502

源码下载 (非本文源码 =_=!!! )
 
                     
                    
                 
                    
                

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号