論壇上經(jīng)常有對P2P原理的討論,但是討論歸討論,很少有實(shí)質(zhì)的東西產(chǎn)生(源代碼)。呵呵,在這里我就用自己實(shí)現(xiàn)的一個(gè)源代碼來說明UDP穿越NAT的原理。
首先先介紹一些基本概念:
NAT(Network Address Translators),網(wǎng)絡(luò)地址轉(zhuǎn)換:網(wǎng)絡(luò)地址轉(zhuǎn)換是在IP地址日益缺乏的情況下產(chǎn)生的,它的主要目的就是為了能夠地址重用。NAT分為兩大類,基本的NAT和NAPT(Network Address/Port Translator)。
最開始NAT是運(yùn)行在路由器上的一個(gè)功能模塊。
最先提出的是基本的NAT,它的產(chǎn)生基于如下事實(shí):一個(gè)私有網(wǎng)絡(luò)(域)中的節(jié)點(diǎn)中只有很少的節(jié)點(diǎn)需要與外網(wǎng)連接(呵呵,這是在上世紀(jì)90年代中期提出的)。那么這個(gè)子網(wǎng)中其實(shí)只有少數(shù)的節(jié)點(diǎn)需要全球唯一的IP地址,其他的節(jié)點(diǎn)的IP地址應(yīng)該是可以重用的。
因此,基本的NAT實(shí)現(xiàn)的功能很簡單,在子網(wǎng)內(nèi)使用一個(gè)保留的IP子網(wǎng)段,這些IP對外是不可見的。子網(wǎng)內(nèi)只有少數(shù)一些IP地址可以對應(yīng)到真正全球唯一的IP地址。如果這些節(jié)點(diǎn)需要訪問外部網(wǎng)絡(luò),那么基本NAT就負(fù)責(zé)將這個(gè)節(jié)點(diǎn)的子網(wǎng)內(nèi)IP轉(zhuǎn)化為一個(gè)全球唯一的IP然后發(fā)送出去。(基本的NAT會改變IP包中的原IP地址,但是不會改變IP包中的端口)
關(guān)于基本的NAT可以參看RFC 1631
另外一種NAT叫做NAPT,從名稱上我們也可以看得出,NAPT不但會改變經(jīng)過這個(gè)NAT設(shè)備的IP數(shù)據(jù)報(bào)的IP地址,還會改變IP數(shù)據(jù)報(bào)的TCP/UDP端口。基本NAT的設(shè)備可能我們見的不多(呵呵,我沒有見到過),NAPT才是我們真正討論的主角。看下圖:
有一個(gè)私有網(wǎng)絡(luò)10.*.*.*,Client A是其中的一臺計(jì)算機(jī),這個(gè)網(wǎng)絡(luò)的網(wǎng)關(guān)(一個(gè)NAT設(shè)備)的外網(wǎng)IP是155.99.25.11(應(yīng)該還有一個(gè)內(nèi)網(wǎng)的IP地址,比如10.0.0.10)。如果Client A中的某個(gè)進(jìn)程(這個(gè)進(jìn)程創(chuàng)建了一個(gè)UDP Socket,這個(gè)Socket綁定1234端口)想訪問外網(wǎng)主機(jī)18.181.0.31的1235端口,那么當(dāng)數(shù)據(jù)包通過NAT時(shí)會發(fā)生什么事情呢?
首先NAT會改變這個(gè)數(shù)據(jù)包的原IP地址,改為155.99.25.11。接著NAT會為這個(gè)傳輸創(chuàng)建一個(gè)Session(Session是一個(gè)抽象的概念,如果是TCP,也許Session是由一個(gè)SYN包開始,以一個(gè)FIN包結(jié)束。而UDP呢,以這個(gè)IP的這個(gè)端口的第一個(gè)UDP開始,結(jié)束呢,呵呵,也許是幾分鐘,也許是幾小時(shí),這要看具體的實(shí)現(xiàn)了)并且給這個(gè)Session分配一個(gè)端口,比如62000,然后改變這個(gè)數(shù)據(jù)包的源端口為62000。所以本來是(10.0.0.1:1234->18.181.0.31:1235)的數(shù)據(jù)包到了互聯(lián)網(wǎng)上變?yōu)榱耍?/SPAN>155.99.25.11:62000->18.181.0.31:1235)。
一旦NAT創(chuàng)建了一個(gè)Session后,NAT會記住62000端口對應(yīng)的是10.0.0.1的1234端口,以后從18.181.0.31發(fā)送到62000端口的數(shù)據(jù)會被NAT自動的轉(zhuǎn)發(fā)到10.0.0.1上。(注意:這里是說18.181.0.31發(fā)送到62000端口的數(shù)據(jù)會被轉(zhuǎn)發(fā),其他的IP發(fā)送到這個(gè)端口的數(shù)據(jù)將被NAT拋棄)這樣Client A就與Server S1建立以了一個(gè)連接。
呵呵,上面的基礎(chǔ)知識可能很多人都知道了,那么下面是關(guān)鍵的部分了。
看看下面的情況:
接上面的例子,如果Client A的原來那個(gè)Socket(綁定了1234端口的那個(gè)UDP Socket)又接著向另外一個(gè)Server S2發(fā)送了一個(gè)UDP包,那么這個(gè)UDP包在通過NAT時(shí)會怎么樣呢?
這時(shí)可能會有兩種情況發(fā)生,一種是NAT再次創(chuàng)建一個(gè)Session,并且再次為這個(gè)Session分配一個(gè)端口號(比如:62001)。另外一種是NAT再次創(chuàng)建一個(gè)Session,但是不會新分配一個(gè)端口號,而是用原來分配的端口號62000。前一種NAT叫做Symmetric NAT,后一種叫做Cone NAT。我們期望我們的NAT是第二種,呵呵,如果你的NAT剛好是第一種,那么很可能會有很多P2P軟件失靈。(可以慶幸的是,現(xiàn)在絕大多數(shù)的NAT屬于后者,即Cone NAT)
好了,我們看到,通過NAT,子網(wǎng)內(nèi)的計(jì)算機(jī)向外連結(jié)是很容易的(NAT相當(dāng)于透明的,子網(wǎng)內(nèi)的和外網(wǎng)的計(jì)算機(jī)不用知道NAT的情況)。
但是如果外部的計(jì)算機(jī)想訪問子網(wǎng)內(nèi)的計(jì)算機(jī)就比較困難了(而這正是P2P所需要的)。
那么我們?nèi)绻霃耐獠堪l(fā)送一個(gè)數(shù)據(jù)報(bào)給內(nèi)網(wǎng)的計(jì)算機(jī)有什么辦法呢?首先,我們必須在內(nèi)網(wǎng)的NAT上打上一個(gè)“洞”(也就是前面我們說的在NAT上建立一個(gè)Session),這個(gè)洞不能由外部來打,只能由內(nèi)網(wǎng)內(nèi)的主機(jī)來打。而且這個(gè)洞是有方向的,比如從內(nèi)部某臺主機(jī)(比如:192.168.0.10)向外部的某個(gè)IP(比如:219.237.60.1)發(fā)送一個(gè)UDP包,那么就在這個(gè)內(nèi)網(wǎng)的NAT設(shè)備上打了一個(gè)方向?yàn)?/SPAN>219.237.60.1的“洞”,(這就是稱為UDP Hole Punching的技術(shù))以后219.237.60.1就可以通過這個(gè)洞與內(nèi)網(wǎng)的192.168.0.10聯(lián)系了。(但是其他的IP不能利用這個(gè)洞)。
呵呵,現(xiàn)在該輪到我們的正題P2P了。有了上面的理論,實(shí)現(xiàn)兩個(gè)內(nèi)網(wǎng)的主機(jī)通訊就差最后一步了:那就是雞生蛋還是蛋生雞的問題了,兩邊都無法主動發(fā)出連接請求,誰也不知道誰的公網(wǎng)地址,那我們?nèi)绾蝸泶蜻@個(gè)洞呢?我們需要一個(gè)中間人來聯(lián)系這兩個(gè)內(nèi)網(wǎng)主機(jī)。
現(xiàn)在我們來看看一個(gè)P2P軟件的流程,以下圖為例:
首先,Client A登錄服務(wù)器,NAT A為這次的Session分配了一個(gè)端口60000,那么Server S收到的Client A的地址是202.187.45.3:60000,這就是Client A的外網(wǎng)地址了。同樣,Client B登錄Server S,NAT B給此次Session分配的端口是40000,那么Server S收到的B的地址是187.34.1.56:40000。
此時(shí),Client A與Client B都可以與Server S通信了。如果Client A此時(shí)想直接發(fā)送信息給Client B,那么他可以從Server S那兒獲得B的公網(wǎng)地址187.34.1.56:40000,是不是Client A向這個(gè)地址發(fā)送信息Client B就能收到了呢?答案是不行,因?yàn)槿绻@樣發(fā)送信息,NAT B會將這個(gè)信息丟棄(因?yàn)檫@樣的信息是不請自來的,為了安全,大多數(shù)NAT都會執(zhí)行丟棄動作)。現(xiàn)在我們需要的是在NAT B上打一個(gè)方向?yàn)?/SPAN>202.187.45.3(即Client A的外網(wǎng)地址)的洞,那么Client A發(fā)送到187.34.1.56:40000的信息,Client B就能收到了。這個(gè)打洞命令由誰來發(fā)呢,呵呵,當(dāng)然是Server S。
總結(jié)一下這個(gè)過程:如果Client A想向Client B發(fā)送信息,那么Client A發(fā)送命令給Server S,請求Server S命令Client B向Client A方向打洞。呵呵,是不是很繞口,不過沒關(guān)系,想一想就很清楚了,何況還有源代碼呢(侯老師說過:在源代碼面前沒有秘密 8)),然后Client A就可以通過Client B的外網(wǎng)地址與Client B通信了。
注意:以上過程只適合于Cone NAT的情況,如果是Symmetric NAT,那么當(dāng)Client B向Client A打洞的端口已經(jīng)重新分配了,Client B將無法知道這個(gè)端口(如果Symmetric NAT的端口是順序分配的,那么我們或許可以猜測這個(gè)端口號,可是由于可能導(dǎo)致失敗的因素太多,我們不推薦這種猜測端口的方法)。
下面是一個(gè)模擬P2P聊天的過程的源代碼,過程很簡單,P2PServer運(yùn)行在一個(gè)擁有公網(wǎng)IP的計(jì)算機(jī)上,P2PClient運(yùn)行在兩個(gè)不同的NAT后(注意,如果兩個(gè)客戶端運(yùn)行在一個(gè)NAT后,本程序很可能不能運(yùn)行正常,這取決于你的NAT是否支持loopback translation,詳見http://midcom-p2p.sourceforge.net/draft-ford-midcom-p2p-01.txt,當(dāng)然,此問題可以通過雙方先嘗試連接對方的內(nèi)網(wǎng)IP來解決,但是這個(gè)代碼只是為了驗(yàn)證原理,并沒有處理這些問題),后登錄的計(jì)算機(jī)可以獲得先登錄計(jì)算機(jī)的用戶名,后登錄的計(jì)算機(jī)通過send username message的格式來發(fā)送消息。如果發(fā)送成功,說明你已取得了直接與對方連接的成功。
程序現(xiàn)在支持三個(gè)命令:send , getu , exit
send格式:send username message
功能:發(fā)送信息給username
getu格式:getu
功能:獲得當(dāng)前服務(wù)器用戶列表
exit格式:exit
功能:注銷與服務(wù)器的連接(服務(wù)器不會自動監(jiān)測客戶是否吊線)
源代碼
注:原文代碼是用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>
/// 服務(wù)器偵聽端口號
/// </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>
/// 客戶端發(fā)送到服務(wù)器的消息基類
/// </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>
/// 服務(wù)器發(fā)送到客戶端消息基類
/// </summary>
public abstract class SCMessage : MessageBase
{}
/// <summary>
/// 請求用戶列表應(yīng)答消息
/// </summary>
public class GetUsersResponseMessage : SCMessage
{
private UserCollection userList;
public GetUsersResponseMessage(UserCollection users)
{
this.userList = users;
}
public UserCollection UserList
{
get { return userList; }
}
}
/// <summary>
/// 轉(zhuǎn)發(fā)請求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>
/// 點(diǎn)對點(diǎn)消息基類
/// </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>
/// 測試應(yīng)答消息
/// </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))
{
// 轉(zhuǎn)換接受的消息
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);
// 發(fā)送應(yīng)答消息
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))
{
// 轉(zhuǎn)換接受的消息
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))
{
// 轉(zhuǎn)換接受的消息
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);
// 獲取目標(biāo)用戶
User toUser = userList.Find(transMsg.ToUserName);
// 轉(zhuǎn)發(fā)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))
{
// 發(fā)送當(dāng)前用戶信息到所有登錄客戶
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;
// 發(fā)送登錄消息到服務(wù)器
P2P.WellKnown.C2S.LoginMessage lginMsg = new P2P.WellKnown.C2S.LoginMessage(userName, password);
byte[] buffer = FormatterHelper.Serialize(lginMsg);
client.Send(buffer, buffer.Length, hostPoint);
// 接受服務(wù)器的登錄應(yīng)答消息
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>
/// 這是主要的函數(shù):發(fā)送一個(gè)消息給某個(gè)用戶(C)
/// 流程:直接向某個(gè)用戶的外網(wǎng)IP發(fā)送消息,如果此前沒有聯(lián)系過
/// 那么此消息將無法發(fā)送,發(fā)送端等待超時(shí)。
/// 超時(shí)后,發(fā)送端將發(fā)送一個(gè)請求信息到服務(wù)端,要求服務(wù)端發(fā)送
/// 給客戶C一個(gè)請求,請求C給本機(jī)發(fā)送打洞消息
/// *以上流程將重復(fù)MAXRETRY次
/// </summary>
/// <param name="toUserName">對方用戶名</param>
/// <param name="message">待發(fā)送的消息</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);
// 等待接收線程將標(biāo)記修改
for (int j=0; j<10; j++)
{
if (this.ReceivedACK)
{
this.ReceivedACK = false;
return true;
}
else
{
Thread.Sleep(300);
}
}
// 沒有接收到目標(biāo)主機(jī)的回應(yīng),認(rèn)為目標(biāo)主機(jī)的端口映射沒有
// 打開,那么發(fā)送請求信息給服務(wù)器,要服務(wù)器告訴目標(biāo)主機(jī)
// 打開映射端口(UDP打洞)
P2P.WellKnown.C2S.TranslateMessage transMsg = new P2P.WellKnown.C2S.TranslateMessage(myName, toUserName);
buffer = FormatterHelper.Serialize(transMsg);
client.Send(buffer, buffer.Length, hostPoint);
// 等待對方先發(fā)送信息
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))
{
// 轉(zhuǎn)換消息
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))
{
// 轉(zhuǎn)換消息
P2P.WellKnown.S2C.SomeOneCallYouMessage purchReqMsg = (P2P.WellKnown.S2C.SomeOneCallYouMessage)msgObj;
// 發(fā)送打洞消息到遠(yuǎn)程主機(jī)
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))
{
// 轉(zhuǎn)換消息
P2P.WellKnown.P2P.WorkMessage workMsg = (P2P.WellKnown.P2P.WorkMessage)msgObj;
Console.WriteLine("Receive a message: {0}", workMsg.Message);
// 發(fā)送應(yīng)答消息
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
}
}