P2P之UDP穿透NAT原理并有UDP打洞的源码

首先先介绍一些基本概念:
    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 的端口是顺序分配的,那么我们或许可以猜测这个端口号,可是由于可能导致失败的因素太多,我们不推荐这种猜测端口的方法)。

另外在网上找到了UDP打洞的不错的代码,希望和大家分享一下。首先声明一下,很多文章都是以前收集的,很多出处已经不知道,望原作者原谅,如有不变请告诉我。
服务器的代码:
None.gif Imports  System.Net
None.gif
Imports  System.Net.Sockets
None.gif
Imports  System.Text
None.gif
Imports  System.Threading
None.gif
Imports  System.Collections
None.gif
ExpandedBlockStart.gifContractedBlock.gif
Module myUDPServer Module myUDPServer
InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif
全局变量#Region "全局变量"
InBlock.gif
InBlock.gif    
Dim ServerSocket As New Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
InBlock.gif    
Dim ipep As IPEndPoint = New IPEndPoint(IPAddress.Any, 12000)
InBlock.gif
InBlock.gif    
Dim htUserList As New Hashtable '用来保存在线用户和用户的"IP和端口"
InBlock.gif

InBlock.gif    
Dim userName(0As String
InBlock.gif    
Dim userIPEP(0As IPEndPoint
InBlock.gif    
Dim userTime(0As Integer
InBlock.gif
InBlock.gif    
Dim timerDelegate As New TimerCallback(AddressOf onLineTimeOut)
InBlock.gif
ExpandedSubBlockEnd.gif
#End Region

InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif
参数#Region "参数"
InBlock.gif
InBlock.gif    
'以下是客户端到服务器端的消息开头
InBlock.gif
    Const LOGININ As String = "10" '请求登陆的消息|||消息形式:10+自己的用户名
InBlock.gif
    Const LOGINOUT As String = "11" '请求登出的消息|||消息形式:11+自己的用户名
InBlock.gif
    Const GETULIST As String = "12" '请求获得在线用户列表|||消息形式:12
InBlock.gif
    Const P2PCONN As String = "13" '请求P2P连接的消息|||消息形式:13+自己的用户名+|+对方的用户名
InBlock.gif
    Const HOLDLINE As String = "14" '保持连接.|||消息开式:14+自己的用户名
InBlock.gif

InBlock.gif    
'以下是服务器到客户端的消息开头
InBlock.gif
    Const HVUSER As String = "20" '用户名已存在
InBlock.gif
    Const GETUSER As String = "21" '在线用户列表|||消息格式:21+用户名+EP
InBlock.gif
    Const MAKHOLD As String = "22" '打洞命令|||消息格式:22+IP
InBlock.gif
    Const LOGINOK As String = "23" '登陆成功
InBlock.gif
    Const SERVCLS As String = "24" '服务器关闭
InBlock.gif
    Const MSGEND As String = "25" '消息结束
InBlock.gif

InBlock.gif    
'以下是服务器端的命名
InBlock.gif
    Const EXITPRO As String = "EXIT" '退出命令
InBlock.gif
    Const SHOWULIST As String = "SHOWUSER" '显示在线用户
InBlock.gif
    Const HELP As String = "HELP" '显示帮助
InBlock.gif

ExpandedSubBlockEnd.gif
#End Region

InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif
方法#Region "方法"
InBlock.gif
InBlock.gif    
'主函数,程序入口
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Sub Main()Sub Main()
InBlock.gif
InBlock.gif        
'获得服务器的IP地址
InBlock.gif
        Dim addressList As System.Net.IPAddress() = Dns.GetHostByName(Dns.GetHostName()).AddressList
InBlock.gif        
Dim ServerIP As IPAddress = addressList(0)
InBlock.gif
InBlock.gif        ServerSocket.Bind(ipep)
InBlock.gif        Console.WriteLine(
"服务器正在启动dot.gif.")
InBlock.gif        Console.WriteLine(
"服务器IP:" & ServerIP.ToString & " 正在监听" & ipep.Port.ToString & "端口")
InBlock.gif        
Dim listenTH As New Thread(AddressOf listen)
InBlock.gif        listenTH.Start() 
'启用监听的线程
InBlock.gif
        Console.WriteLine("服务器启动成功dot.gif..")
InBlock.gif
InBlock.gif        
Dim timer As New Timer(timerDelegate, Nothing05000)
InBlock.gif
InBlock.gif        
Dim SVInput As String
InBlock.gif        
While True
InBlock.gif            Console.Write(
"Server>")
InBlock.gif            SVInput 
= Console.ReadLine().ToUpper
InBlock.gif            
Select Case SVInput
InBlock.gif                
Case EXITPRO
InBlock.gif                    listenTH.Abort()
InBlock.gif                    ServerSocket.Close()
InBlock.gif                    
Exit Sub
InBlock.gif                
Case SHOWULIST
InBlock.gif                    showUser()
InBlock.gif                
Case HELP
InBlock.gif                    Console.Write(
"*********************************" & Chr(10& Chr(13& "exit:输出当前程序" & Chr(10& Chr(13& "showuser:显示当前在线用户例表" & Chr(10& Chr(13& "help:显示帮助" & Chr(10& Chr(13& "*********************************" & Chr(10& Chr(13))
InBlock.gif                
Case Else
InBlock.gif                    Console.WriteLine(
"*********************************" & Chr(10& Chr(13& "笨瓜,你输入的不是有效的命令." & Chr(10& Chr(13& "*********************************")
InBlock.gif            
End Select
InBlock.gif        
End While
InBlock.gif
InBlock.gif
ExpandedSubBlockEnd.gif    
End Sub

InBlock.gif
InBlock.gif    
'打印在线用户
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Sub showUser()Sub showUser()
InBlock.gif        
Dim hava As Boolean = False
InBlock.gif        
If userName.Length <> 0 Then
InBlock.gif            
Dim i As Integer
InBlock.gif            
For i = 1 To userName.Length - 1
InBlock.gif                
If userName(i) <> "" Then
InBlock.gif                    hava 
= True
InBlock.gif                    
Exit For
InBlock.gif                
End If
InBlock.gif            
Next
InBlock.gif            
If hava = False Then
InBlock.gif                Console.WriteLine(
"*********************************" & Chr(10& Chr(13& "当前没有用户在线" & Chr(10& Chr(13& "*********************************")
InBlock.gif                
Exit Sub
InBlock.gif            
End If
InBlock.gif            Console.WriteLine(
"*********************************")
InBlock.gif            
For i = 1 To userName.Length - 1
InBlock.gif                
If userName(i) <> "" Then
InBlock.gif                    Console.WriteLine(
"用户名:" & userName(i) & " 地址:" & userIPEP(i).ToString)
InBlock.gif                
End If
InBlock.gif            
Next
InBlock.gif            Console.WriteLine(
"*********************************")
InBlock.gif        
Else
InBlock.gif            Console.WriteLine(
"*********************************" & Chr(10& Chr(13& "当前没有用户在线" & Chr(10& Chr(13& "*********************************")
InBlock.gif        
End If
ExpandedSubBlockEnd.gif    
End Sub

InBlock.gif
InBlock.gif    
'服务器监听函数
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Sub listen()Sub listen()
InBlock.gif
InBlock.gif        
While True
InBlock.gif
InBlock.gif            
Try
InBlock.gif                
Dim recv As Integer = 0
InBlock.gif                
Dim data As [Byte]() = New Byte(1024) {}
InBlock.gif                
Dim sender As New IPEndPoint(IPAddress.Any, 0)
InBlock.gif                
Dim tempRemoteEP As EndPoint = CType(sender, EndPoint)
InBlock.gif                recv 
= ServerSocket.ReceiveFrom(data, tempRemoteEP)
InBlock.gif
InBlock.gif                
'Console.WriteLine(Encoding.Unicode.GetString(data))
InBlock.gif

InBlock.gif                
Dim msgHead As String = Encoding.Unicode.GetString(data, 04)
InBlock.gif                
Select Case msgHead
InBlock.gif                    
Case LOGININ
InBlock.gif                        
Dim LoginThing As String = userLogin(data, tempRemoteEP, recv)
InBlock.gif                        
If LoginThing = HVUSER Then
InBlock.gif                            sendMsg(HVUSER, tempRemoteEP)
InBlock.gif                        
ElseIf LoginThing = LOGINOK Then
InBlock.gif                            sendMsg(LOGINOK, tempRemoteEP)
InBlock.gif
InBlock.gif                        
End If
InBlock.gif
InBlock.gif                    
Case LOGINOUT
InBlock.gif                        userloginout(data, recv)
InBlock.gif
InBlock.gif                    
Case GETULIST
InBlock.gif                        
Dim userinfo As String = getUserList()
InBlock.gif                        sendMsg(userinfo, tempRemoteEP)
InBlock.gif
InBlock.gif                    
Case P2PCONN
InBlock.gif                        questP2PConn(data, recv)
InBlock.gif
InBlock.gif                    
Case HOLDLINE
InBlock.gif                        holdOnLine(data, recv)
InBlock.gif                
End Select
InBlock.gif
InBlock.gif            
Catch e As Exception
InBlock.gif                
'Console.WriteLine(e.ToString)
InBlock.gif
            End Try
InBlock.gif        
End While
InBlock.gif
ExpandedSubBlockEnd.gif    
End Sub

InBlock.gif
InBlock.gif    
'转发P2P连接请求
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Private Sub questP2PConn()Sub questP2PConn(ByVal data() As ByteByVal recv As Integer)
InBlock.gif
InBlock.gif        
Dim recvStr As String = Encoding.Unicode.GetString(data, 4, recv - 4)
InBlock.gif        
Dim split() As String = recvStr.Split("|")
InBlock.gif
InBlock.gif        
Dim fromEP As IPEndPoint
InBlock.gif        
Dim toEP As IPEndPoint
InBlock.gif        
Dim i As Integer
InBlock.gif        
For i = 1 To userName.Length - 1
InBlock.gif            
If userName(i) = split(0Then
InBlock.gif                fromEP 
= userIPEP(i)
InBlock.gif            
End If
InBlock.gif            
If userName(i) = split(1Then
InBlock.gif                toEP 
= userIPEP(i)
InBlock.gif            
End If
InBlock.gif        
Next
InBlock.gif        
Dim holdbytes() As Byte = Encoding.Unicode.GetBytes(MAKHOLD & fromEP.ToString)
InBlock.gif        ServerSocket.SendTo(holdbytes, toEP)
ExpandedSubBlockEnd.gif    
End Sub

InBlock.gif
InBlock.gif    
'函数.返回所有在线用户.其格式:用户名+|+用户IPEP+|
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Private Function getUserList()Function getUserList() As String
InBlock.gif        
Dim userInfo As String = GETUSER
InBlock.gif        
Dim i As Integer
InBlock.gif        
For i = 1 To userName.Length - 1
InBlock.gif            
If userName(i) <> "" Then
InBlock.gif                userInfo 
+= userName(i) & "|" & userIPEP(i).ToString & "|"
InBlock.gif            
End If
InBlock.gif        
Next
InBlock.gif        
Return userInfo
ExpandedSubBlockEnd.gif    
End Function

InBlock.gif
InBlock.gif    
'用户登陆,直接返回登陆是否成功的值
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Private Function userLogin()Function userLogin(ByVal data As Byte(), ByVal userEP As IPEndPoint, ByVal recvCount As IntegerAs String
InBlock.gif
InBlock.gif        
Dim Uname As String = Encoding.Unicode.GetString(data, 4, recvCount - 4)
InBlock.gif
InBlock.gif        
Dim Uinfobytes() As Byte
InBlock.gif
InBlock.gif        
Dim i As Integer
InBlock.gif        
Dim j As Integer
InBlock.gif
InBlock.gif        
For i = 1 To userName.Length - 1
InBlock.gif            
If Uname = userName(i) Then
InBlock.gif                
Return HVUSER
InBlock.gif            
End If
InBlock.gif        
Next
InBlock.gif
InBlock.gif        
For i = 1 To userName.Length - 1
InBlock.gif            
If userName(i) = "" Then
InBlock.gif                userName(i) 
= Uname
InBlock.gif                userIPEP(i) 
= userEP
InBlock.gif                userTime(i) 
= 60
InBlock.gif                Console.Write(
Chr(10& Chr(13& "*********************************" & Chr(10& Chr(13& Uname.Trim & "上线了." & "用户地址:" & userEP.ToString & Chr(10& Chr(13& "*********************************" & Chr(10& Chr(13))
InBlock.gif                Console.Write(
"Server>")
InBlock.gif
InBlock.gif                Uinfobytes 
= Encoding.Unicode.GetBytes(LOGININ & userName(i) & "|" & userIPEP(i).ToString)
InBlock.gif
InBlock.gif                
For j = 1 To userName.Length - 1
InBlock.gif                    
If userName(j) <> "" And userName(j) <> Uname Then
InBlock.gif                        ServerSocket.SendTo(Uinfobytes, userIPEP(j))
InBlock.gif                    
End If
InBlock.gif                
Next
InBlock.gif                
Return LOGINOK
InBlock.gif            
End If
InBlock.gif        
Next
InBlock.gif
InBlock.gif        
Dim userCount As Integer = userName.Length
InBlock.gif
InBlock.gif        
ReDim Preserve userName(userCount)
InBlock.gif        
ReDim Preserve userIPEP(userCount)
InBlock.gif        
ReDim Preserve userTime(userCount)
InBlock.gif
InBlock.gif        userName(userName.Length 
- 1= Uname
InBlock.gif        userIPEP(userIPEP.Length 
- 1= userEP
InBlock.gif        userTime(userTime.Length 
- 1= 60
InBlock.gif
InBlock.gif        Console.Write(
Chr(10& Chr(13& "*********************************" & Chr(10& Chr(13& Uname.Trim & "上线了." & "用户地址:" & userEP.ToString & Chr(10& Chr(13& "*********************************" & Chr(10& Chr(13))
InBlock.gif        Console.Write(
"Server>")
InBlock.gif
InBlock.gif        Uinfobytes 
= Encoding.Unicode.GetBytes(LOGININ & userName(userName.Length - 1& "|" & userIPEP(userName.Length - 1).ToString)
InBlock.gif
InBlock.gif        
For j = 1 To userName.Length - 1
InBlock.gif            
If userName(j) <> "" And userName(j) <> Uname Then
InBlock.gif                ServerSocket.SendTo(Uinfobytes, userIPEP(j))
InBlock.gif            
End If
InBlock.gif        
Next
InBlock.gif        
Return LOGINOK
InBlock.gif
ExpandedSubBlockEnd.gif    
End Function

InBlock.gif
InBlock.gif    
'用户登出
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Private Sub userloginout()Sub userloginout(ByVal data As Byte(), ByVal recvCount As Integer)
InBlock.gif
InBlock.gif        
Dim i As Integer
InBlock.gif        
Dim Uname As String = Encoding.Unicode.GetString(data, 4, recvCount - 4)
InBlock.gif
InBlock.gif        
For i = 1 To userName.Length - 1
InBlock.gif
InBlock.gif            
If Uname = userName(i) Then
InBlock.gif
InBlock.gif                
Dim loginOutMsg As String = LOGINOUT & userName(i)
InBlock.gif
InBlock.gif
InBlock.gif                userName(i) 
= ""
InBlock.gif                userIPEP(i) 
= Nothing
InBlock.gif                userTime(i) 
= 0
InBlock.gif
InBlock.gif                
Dim j As Integer
InBlock.gif                
For j = 1 To userName.Length - 1
InBlock.gif                    
If userName(j) <> "" Then
InBlock.gif
InBlock.gif                        sendMsg(loginOutMsg, userIPEP(j))
InBlock.gif
InBlock.gif                    
End If
InBlock.gif                
Next
InBlock.gif
InBlock.gif                Console.WriteLine(
Chr(10& Chr(13& "*********************************")
InBlock.gif                Console.WriteLine(
"用户" & Uname & "下线了.")
InBlock.gif                Console.WriteLine(
"*********************************")
InBlock.gif                Console.Write(
"Server>")
InBlock.gif
InBlock.gif                
Exit For
InBlock.gif
InBlock.gif            
End If
InBlock.gif
InBlock.gif        
Next
InBlock.gif
ExpandedSubBlockEnd.gif    
End Sub

InBlock.gif
InBlock.gif    
'保持用户在线的过程
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Private Sub holdOnLine()Sub holdOnLine(ByVal data As Byte(), ByVal recvCount As Integer)
InBlock.gif
InBlock.gif        
Dim Uname As String = Encoding.Unicode.GetString(data, 4, recvCount - 4)
InBlock.gif
InBlock.gif        
Dim i As Integer
InBlock.gif
InBlock.gif        
For i = 1 To userName.Length - 1
InBlock.gif
InBlock.gif            
If Uname = userName(i) Then
InBlock.gif
InBlock.gif                userTime(i) 
= 60
InBlock.gif                
Exit For
InBlock.gif
InBlock.gif            
End If
InBlock.gif
InBlock.gif        
Next
InBlock.gif
ExpandedSubBlockEnd.gif    
End Sub

InBlock.gif
InBlock.gif    
'用户超时退出
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Private Sub onLineTimeOut()Sub onLineTimeOut(ByVal state As [Object])
InBlock.gif
InBlock.gif        
Dim i As Integer
InBlock.gif
InBlock.gif        
For i = 1 To userName.Length - 1
InBlock.gif
InBlock.gif            
If userTime(i) > 0 Then
InBlock.gif
InBlock.gif                userTime(i) 
-= 5
InBlock.gif
InBlock.gif                
If userTime(i) <= 0 Then
InBlock.gif
InBlock.gif                    
Dim loginoutmsg As String = LOGINOUT & userName(i)
InBlock.gif
InBlock.gif                    Console.WriteLine(
Chr(10& Chr(13& "*********************************")
InBlock.gif                    Console.WriteLine(
"用户" & userName(i) & "下线了.")
InBlock.gif                    Console.WriteLine(
"*********************************")
InBlock.gif                    Console.Write(
"Server>")
InBlock.gif
InBlock.gif                    userName(i) 
= ""
InBlock.gif                    userIPEP(i) 
= Nothing
InBlock.gif
InBlock.gif                    
Dim ULoginOutbytes() As Byte = Encoding.Unicode.GetBytes(loginoutmsg)
InBlock.gif
InBlock.gif                    
Dim j As Integer
InBlock.gif                    
For j = 1 To userName.Length - 1
InBlock.gif
InBlock.gif                        
If userName(j) <> "" Then
InBlock.gif                            
If userIPEP(j) Is Nothing Then
InBlock.gif                            
Else
InBlock.gif                                ServerSocket.SendTo(ULoginOutbytes, userIPEP(j))
InBlock.gif                            
End If
InBlock.gif                        
End If
InBlock.gif
InBlock.gif                    
Next
InBlock.gif
InBlock.gif                
End If
InBlock.gif
InBlock.gif            
End If
InBlock.gif
InBlock.gif        
Next
InBlock.gif
ExpandedSubBlockEnd.gif    
End Sub

InBlock.gif
InBlock.gif    
'发送消息的函数
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Sub sendMsg()Sub sendMsg(ByVal msg As StringByVal remoteEP As IPEndPoint)
InBlock.gif        
Dim sendBytes As [Byte]() = Encoding.Unicode.GetBytes(msg)
InBlock.gif        
Try
InBlock.gif
InBlock.gif            ServerSocket.SendTo(sendBytes, remoteEP)
InBlock.gif
InBlock.gif        
Catch e As Exception
InBlock.gif            Console.WriteLine(e.ToString())
InBlock.gif        
End Try
ExpandedSubBlockEnd.gif    
End Sub

InBlock.gif
ExpandedSubBlockEnd.gif
#End Region

InBlock.gif
ExpandedBlockEnd.gif
End Module

None.gif
客户端的代码:
None.gif Imports  System.Net
None.gif
Imports  System.Net.Sockets
None.gif
Imports  System.Text
None.gif
Imports  System.Threading
None.gif
None.gif
ExpandedBlockStart.gifContractedBlock.gif
Module Module1 Module Module1
InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif
参数#Region "参数"
InBlock.gif
InBlock.gif    
'以下是客户端到服务器端的消息开头
InBlock.gif
    Const LOGININ As String = "10" '请求登陆的消息|||消息形式:10+自己的用户名
InBlock.gif
    Const LOGINOUT As String = "11" '请求登出的消息|||消息形式:11+自己的用户名
InBlock.gif
    Const GETULIST As String = "12" '请求获得在线用户列表|||消息形式:12+自己的用户名
InBlock.gif
    Const P2PCONN As String = "13" '请求P2P连接的消息|||消息形式:13+自己的用户名+对方的用户名
InBlock.gif
    Const HOLDLINE As String = "14" '保持连接.|||消息开式:14+自己的用户名
InBlock.gif

InBlock.gif    
'以下是服务器到客户端的消息开头
InBlock.gif
    Const HVUSER As String = "20" '用户名已存在
InBlock.gif
    Const GETUSER As String = "21" '在线用户列表|||消息格式:21+用户名+EP
InBlock.gif
    Const MAKHOLD As String = "22" '打洞命令|||消息格式:22+IP
InBlock.gif
    Const LOGINOK As String = "23" '登陆成功
InBlock.gif
    Const SERVCLS As String = "24" '服务器关闭
InBlock.gif
    Const MSGEND As String = "25" '消息结束
InBlock.gif

InBlock.gif    
'以下是客户端到客户端的消息开头
InBlock.gif
    Const HOLDOK As String = "30" '打洞成功
InBlock.gif
    Const CHATMSG As String = "31" '聊天消息
InBlock.gif
    Const CHTMSGEND As String = "32" '聊天消息发送成功
InBlock.gif

InBlock.gif    
'以下是客户端的命名
InBlock.gif
    Const EXITPRO As String = "EXIT" '退出命令
InBlock.gif
    Const SHOWULIST As String = "SHOWUSER" '显示在线用户
InBlock.gif
    Const HELP As String = "HELP" '显示帮助
InBlock.gif
    Const SEND As String = "SEND" '发送消息
InBlock.gif

ExpandedSubBlockEnd.gif
#End Region

InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif
全局全量#Region "全局全量"
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
Delegate Sub myMethodDelegate()Sub myMethodDelegate(ByRef myInData As Byte()) '登陆时用的事件
InBlock.gif

InBlock.gif    
'Dim MaxTry As Integer = 5
InBlock.gif
    Dim msgSendEnd As Boolean = False '消息是否发送成功,若发送成功,则会返回结束消息
InBlock.gif
    Dim ThListen As New Thread(AddressOf listen) '监听的线程
InBlock.gif
    Dim ClientSocket As New Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp) '客户端套节字的定义
InBlock.gif
    Dim username As String '当前用户名
InBlock.gif
    Dim ServerEP As IPEndPoint '服务器的IPEP
InBlock.gif
    Dim holdBytes As [Byte]() = Encoding.Unicode.GetBytes(HOLDLINE & username) '和服务器保持连接连接时用到的byte数组
InBlock.gif
    Dim OLUserName() As String
InBlock.gif    
Dim OLUserEP() As IPEndPoint
InBlock.gif    
Dim getUrecCount As Integer
InBlock.gif    
Dim testHold As Boolean = False
InBlock.gif    
Dim testChat As Boolean = False
InBlock.gif
InBlock.gif    
Private receiveDone As ManualResetEvent '在登陆时用来阻塞线程,等待收到数据
InBlock.gif
    Private sendDone As ManualResetEvent '用来阴塞发送消息的线程.等待收到回送的确认消息
InBlock.gif
    Private getUDone As ManualResetEvent '用来阻塞请求好友名单的线程,等待接收好友名单
InBlock.gif
    Private holdDone As ManualResetEvent '用来阻塞打洞时的线程
InBlock.gif
    Private chatDone As ManualResetEvent '用来阻塞发送聊天消息时的线程
InBlock.gif

InBlock.gif    
Dim timerDelegate As New TimerCallback(AddressOf holdonline) '为保持在线状态弄得
InBlock.gif

ExpandedSubBlockEnd.gif
#End Region

InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif
方法#Region "方法"
InBlock.gif
InBlock.gif    
'主函数,程序入口
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Sub Main()Sub Main()
InBlock.gif        
Dim InputIP As String
InBlock.gif        
Dim InputOK As Boolean = False
InBlock.gif
InBlock.gif
InBlock.gif        
'判断输入的IP,并且保存服务器的IPEP
InBlock.gif
        While InputOK <> True
InBlock.gif            Console.Write(
"请输入服务器IP:")
InBlock.gif            InputIP 
= Console.ReadLine()
InBlock.gif            
Try
InBlock.gif                ServerEP 
= New IPEndPoint(IPAddress.Parse(InputIP), 11000)
InBlock.gif                InputOK 
= True
InBlock.gif            
Catch
InBlock.gif                Console.WriteLine(
"你输入的服务器IP不正确,请重新输入.")
InBlock.gif                InputOK 
= False
InBlock.gif            
End Try
InBlock.gif        
End While
InBlock.gif
InBlock.gif        
Dim bool As Boolean = False
InBlock.gif
InBlock.gif        
'判断用户是否登陆成功
InBlock.gif
        While bool <> True
InBlock.gif
InBlock.gif            
Dim LoginOK As Boolean = Login()
InBlock.gif            
If LoginOK = True Then
InBlock.gif                bool 
= True
InBlock.gif            
Else
InBlock.gif                Console.Write(
"是否重试:输入Y重试,输入任意值退出程序:")
InBlock.gif                
Dim tempYN As String = Console.ReadLine.ToUpper
InBlock.gif                
If tempYN = "Y" Then
InBlock.gif                    bool 
= False
InBlock.gif                
Else
InBlock.gif                    
Exit Sub
InBlock.gif                
End If
InBlock.gif            
End If
InBlock.gif
InBlock.gif        
End While
InBlock.gif
InBlock.gif        Console.WriteLine(
"用户名:" & username)
InBlock.gif        holdBytes 
= Encoding.Unicode.GetBytes(HOLDLINE & username)
InBlock.gif        
'登陆成功后.用一个timer,每隔50秒向服务器发送消息,保持在线状态跟在主机注册的端口
InBlock.gif
        Dim timer As New Timer(timerDelegate, Nothing1000050000)
InBlock.gif
InBlock.gif        
'请求在线名单
InBlock.gif
        Console.WriteLine("正在获取在线名单,请稍后dot.gif.")
InBlock.gif        
Dim getUbool As Boolean = False
InBlock.gif        
While getUbool <> True
InBlock.gif            getUbool 
= getU()
InBlock.gif            
If getUbool = False Then
InBlock.gif                Console.Write(
"是否重试:输入Y重试,输入任意值退出程序:")
InBlock.gif                
Dim tempYN As String = Console.ReadLine.ToUpper
InBlock.gif                
If tempYN = "Y" Then
InBlock.gif                    bool 
= False
InBlock.gif                
Else
InBlock.gif                    
Exit Sub
InBlock.gif                
End If
InBlock.gif            
End If
InBlock.gif        
End While
InBlock.gif
InBlock.gif        ThListen.Start()
InBlock.gif
InBlock.gif        
'用来处理客户端的一些命令
InBlock.gif
        Dim SVInput As String
InBlock.gif        
While True
InBlock.gif            Console.Write(
"Client>")
InBlock.gif            SVInput 
= Console.ReadLine().ToUpper
InBlock.gif            
Select Case SVInput
InBlock.gif                
Case EXITPRO
InBlock.gif                    exitApp()
InBlock.gif                    ThListen.Abort()
InBlock.gif                    ClientSocket.Close()
InBlock.gif                    
Exit Sub
InBlock.gif                
Case SHOWULIST
InBlock.gif                    Console.WriteLine(
"*********************************")
InBlock.gif                    showUserList()
InBlock.gif                    Console.WriteLine(
"*********************************")
InBlock.gif                
Case HELP
InBlock.gif                    Console.Write(
"*********************************" & Chr(10& Chr(13& "exit:输出当前程序" & Chr(10& Chr(13& "showuser:显示当前在线用户例表" & Chr(10& Chr(13& "send:发送消息.格式:send 用户名 消息" & Chr(10& Chr(13& "help:显示帮助" & Chr(10& Chr(13& "*********************************" & Chr(10& Chr(13))
InBlock.gif                
Case Else
InBlock.gif                    
If SVInput.Substring(04= "SEND" Then
InBlock.gif                        
Dim split() As String = SVInput.Split(" ")
InBlock.gif                        
If split.Length = 3 Then
InBlock.gif                            sendChatMsg(
split(1), split(2))
InBlock.gif                        
Else
InBlock.gif                            Console.WriteLine(
"*********************************" & Chr(10& Chr(13& "你输入的命令格式不正确.send命令格式为:send 用户名 你的消息" & Chr(10& Chr(13& "*********************************")
InBlock.gif                        
End If
InBlock.gif                    
Else
InBlock.gif                        Console.WriteLine(
"*********************************" & Chr(10& Chr(13& "笨瓜,你输入的不是有效的命令." & Chr(10& Chr(13& "*********************************")
InBlock.gif                    
End If
InBlock.gif            
End Select
InBlock.gif        
End While
InBlock.gif
ExpandedSubBlockEnd.gif    
End Sub

InBlock.gif
InBlock.gif    
'登陆函数
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Private Function Login()Function Login() As Boolean
InBlock.gif
InBlock.gif        receiveDone 
= New ManualResetEvent(False)
InBlock.gif        
Dim userBytes As [Byte]()
InBlock.gif
InBlock.gif        
Dim userOK As Boolean = False
InBlock.gif
InBlock.gif        Console.Write(
"请输入你的用户名:")
InBlock.gif
InBlock.gif        
'判断用户名是否符合格式
InBlock.gif
        While (userOK <> True)
InBlock.gif            username 
= Console.ReadLine.ToUpper
InBlock.gif            userBytes 
= Encoding.Unicode.GetBytes(LOGININ & username)
InBlock.gif
InBlock.gif            
If userBytes.Length > 24 Or userBytes.Length < 10 Then
InBlock.gif                Console.WriteLine(
"用户名不得小于6个字节,且不得大于20个字节.")
InBlock.gif                Console.Write(
"请重新输入你的用户名:")
InBlock.gif            
Else
InBlock.gif                userOK 
= True
InBlock.gif            
End If
InBlock.gif        
End While
InBlock.gif
InBlock.gif        
'向服务器发送客户消息
InBlock.gif
        ClientSocket.SendTo(userBytes, ServerEP)
InBlock.gif
InBlock.gif        
Dim data As [Byte]() = New Byte(1024) {}
InBlock.gif
InBlock.gif        
Dim comStr As String = Encoding.Unicode.GetString(data, 04)
InBlock.gif
InBlock.gif        
'异面的接收服务器回送的消息
InBlock.gif
        Dim DGrecv As New myMethodDelegate(AddressOf recvLogin)
InBlock.gif        DGrecv.BeginInvoke(data, 
NothingNothing)
InBlock.gif
InBlock.gif        
'等待服务器回送消息的时长为10秒,否则为服务器超时
InBlock.gif
        receiveDone.WaitOne(30000True)
InBlock.gif
InBlock.gif        
Dim recvStr As String = Encoding.Unicode.GetString(data, 04)
InBlock.gif
InBlock.gif        
If recvStr = comStr Then
InBlock.gif            Console.WriteLine(
"服务器超时.登陆失败!!")
InBlock.gif            
Return False
InBlock.gif        
End If
InBlock.gif
InBlock.gif        
If Encoding.Unicode.GetString(data, 04= LOGINOK Then
InBlock.gif            Console.WriteLine(
"登陆成功!!")
InBlock.gif            
Return True
InBlock.gif        
ElseIf Encoding.Unicode.GetString(data, 04= HVUSER Then
InBlock.gif            Console.WriteLine(
"用户名重复.登陆失败!!")
InBlock.gif            
Return False
InBlock.gif        
Else
InBlock.gif            Console.WriteLine(
"服务器未知错误,登陆失败!!")
InBlock.gif            
Return False
InBlock.gif        
End If
InBlock.gif
ExpandedSubBlockEnd.gif    
End Function

InBlock.gif
InBlock.gif    
'登出函数
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Private Sub exitApp()Sub exitApp()
InBlock.gif
InBlock.gif        
Dim loginOutStr As String = LOGINOUT & username
InBlock.gif        
Dim sendBytes As [Byte]() = Encoding.Unicode.GetBytes(loginOutStr)
InBlock.gif        ClientSocket.SendTo(sendBytes, ServerEP)
InBlock.gif
ExpandedSubBlockEnd.gif    
End Sub

InBlock.gif
InBlock.gif    
'请求好友列表的函数
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Private Function getU()Function getU() As Boolean
InBlock.gif
InBlock.gif        getUDone 
= New ManualResetEvent(False)
InBlock.gif        
Dim getUbytes As Byte() = Encoding.Unicode.GetBytes(GETULIST)
InBlock.gif        ClientSocket.SendTo(getUbytes, ServerEP)
InBlock.gif
InBlock.gif        
Dim data As [Byte]() = New Byte(4056) {}
InBlock.gif        
Dim comStr As String = Encoding.Unicode.GetString(data, 04)
InBlock.gif
InBlock.gif        
Dim GUrecv As New myMethodDelegate(AddressOf recvGetU)
InBlock.gif        GUrecv.BeginInvoke(data, 
NothingNothing)
InBlock.gif
InBlock.gif        getUDone.WaitOne(
30000True)
InBlock.gif
InBlock.gif        
Dim recvStr As String = Encoding.Unicode.GetString(data, 04)
InBlock.gif
InBlock.gif        
If recvStr = comStr Then
InBlock.gif            Console.WriteLine(
"服务器超时.或取好友名单失败!!")
InBlock.gif            
Return False
InBlock.gif        
End If
InBlock.gif
InBlock.gif        
If Encoding.Unicode.GetString(data, 04= GETUSER Then
InBlock.gif            getUserList(data, getUrecCount)
InBlock.gif            Console.WriteLine(
"获取在线名单成功!!")
InBlock.gif            showUserList()
InBlock.gif            
Return True
InBlock.gif        
Else
InBlock.gif            Console.WriteLine(
"服务器未知错误,获取在线名单失败!!")
InBlock.gif            
Return False
InBlock.gif        
End If
InBlock.gif
ExpandedSubBlockEnd.gif    
End Function

InBlock.gif
InBlock.gif    
'登陆时用来异步的接收服务器发送的消息
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Sub recvLogin()Sub recvLogin(ByRef inData As Byte())
InBlock.gif
InBlock.gif        ClientSocket.Receive(inData)
InBlock.gif        receiveDone.Set()
InBlock.gif
ExpandedSubBlockEnd.gif    
End Sub

InBlock.gif
InBlock.gif    
'请求好友名单时用来异步接收服务器发送的消息
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Sub recvGetU()Sub recvGetU(ByRef inData As Byte())
InBlock.gif
InBlock.gif        getUrecCount 
= ClientSocket.Receive(inData)
InBlock.gif        getUDone.Set()
InBlock.gif
ExpandedSubBlockEnd.gif    
End Sub

InBlock.gif
InBlock.gif    
'处理收到的在线用户信息
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Private Sub getUserList()Sub getUserList(ByVal userInfobytes() As ByteByVal reccount As Integer)
InBlock.gif
InBlock.gif        
Dim ustr As String = Encoding.Unicode.GetString(userInfobytes, 4, reccount - 4)
InBlock.gif
InBlock.gif        
Dim splitStr() As String = Nothing
InBlock.gif
InBlock.gif        splitStr 
= Ustr.Split("|")
InBlock.gif
InBlock.gif        
Dim IPEPSplit() As String = Nothing
InBlock.gif
InBlock.gif        
Dim i As Integer = 0
InBlock.gif
InBlock.gif        
Dim k As Integer
InBlock.gif        
For k = 0 To splitStr.Length - 2 Step 2
InBlock.gif            
ReDim Preserve OLUserName(i)
InBlock.gif            
ReDim Preserve OLUserEP(i)
InBlock.gif
InBlock.gif            OLUserName(i) 
= splitStr(k)
InBlock.gif            IPEPSplit 
= splitStr(k + 1).Split(":")
InBlock.gif            OLUserEP(i) 
= New IPEndPoint(IPAddress.Parse(IPEPSplit(0)), IPEPSplit(1))
InBlock.gif
InBlock.gif            IPEPSplit 
= Nothing
InBlock.gif            i 
+= 1
InBlock.gif        
Next
InBlock.gif
ExpandedSubBlockEnd.gif    
End Sub

InBlock.gif
InBlock.gif    
'显示在线用户
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Private Sub showUserList()Sub showUserList()
InBlock.gif        
Dim i As Integer
InBlock.gif        
For i = 0 To OLUserName.Length - 1
InBlock.gif            
If OLUserName(i) <> "" Then
InBlock.gif                Console.WriteLine(
"用户名:" & OLUserName(i) & " 用户IP:" & OLUserEP(i).ToString)
InBlock.gif            
End If
InBlock.gif        
Next
ExpandedSubBlockEnd.gif    
End Sub

InBlock.gif
InBlock.gif    
'客户程序监听的函数
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Sub listen()Sub listen()
InBlock.gif
InBlock.gif        
While True
InBlock.gif
InBlock.gif            
Try
InBlock.gif                
Dim recv As Integer = 0 '收到的字节数
InBlock.gif
                Dim data As [Byte]() = New Byte(1024) {} '缓冲区大小
InBlock.gif
                Dim sender As New IPEndPoint(IPAddress.Any, 0)
InBlock.gif                
Dim tempRemoteEP As EndPoint = CType(sender, EndPoint)
InBlock.gif                recv 
= ClientSocket.ReceiveFrom(data, tempRemoteEP)
InBlock.gif
InBlock.gif                
Dim msgHead As String = Encoding.Unicode.GetString(data, 04'获得消息头的内容
InBlock.gif
                Select Case msgHead
InBlock.gif                    
Case MSGEND
InBlock.gif                        msgSendEnd 
= True
InBlock.gif                        sendDone.Set()
InBlock.gif                    
Case LOGININ
InBlock.gif                        addOnLine(data, recv)
InBlock.gif                    
Case LOGINOUT
InBlock.gif                        removeOnLine(data, recv)
InBlock.gif                    
Case MSGEND
InBlock.gif                        msgSendEnd 
= True
InBlock.gif                        sendDone.Set()
InBlock.gif                    
Case MAKHOLD
InBlock.gif                        Console.WriteLine(
Chr(10& Chr(13& "收到打洞消息.")
InBlock.gif                        makeHold(data, recv)
InBlock.gif                        Console.Write(
"Client>")
InBlock.gif                    
Case CHATMSG
InBlock.gif                        showChatMsg(data, recv)
InBlock.gif                    
Case HOLDOK
InBlock.gif                        testHold 
= True
InBlock.gif                        holdDone.Set()
InBlock.gif                    
Case CHTMSGEND
InBlock.gif                        testChat 
= True
InBlock.gif                        chatDone.Set()
InBlock.gif                
End Select
InBlock.gif
InBlock.gif            
Catch
InBlock.gif            
End Try
InBlock.gif
InBlock.gif        
End While
ExpandedSubBlockEnd.gif    
End Sub

InBlock.gif
InBlock.gif    
'发送聊天消息
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Private Sub sendChatMsg()Sub sendChatMsg(ByVal remoteUser As StringByVal chatMsgStr As String)
InBlock.gif
InBlock.gif        
If remoteUser = username Then
InBlock.gif            Console.WriteLine(
"猪头,你想干什么!!!")
InBlock.gif            
Exit Sub
InBlock.gif        
End If
InBlock.gif
InBlock.gif        
Dim i As Integer
InBlock.gif
InBlock.gif        
Dim remoteUEP As IPEndPoint
InBlock.gif        
For i = 0 To OLUserName.Length - 1
InBlock.gif            
If remoteUser = OLUserName(i) Then
InBlock.gif                remoteUEP 
= OLUserEP(i)
InBlock.gif                
Exit For
InBlock.gif            
End If
InBlock.gif            
If i = OLUserName.Length - 1 Then
InBlock.gif                Console.WriteLine(
"找不到你想发送的用户.")
InBlock.gif                
Exit Sub
InBlock.gif            
End If
InBlock.gif        
Next
InBlock.gif
InBlock.gif        
Dim msgbytes() As Byte = Encoding.Unicode.GetBytes(CHATMSG & username & "|" & chatMsgStr)
InBlock.gif        
Dim holdbytes() As Byte = Encoding.Unicode.GetBytes(P2PCONN & username & "|" & remoteUser)
InBlock.gif
InBlock.gif        chatDone 
= New ManualResetEvent(False)
InBlock.gif        ClientSocket.SendTo(msgbytes, remoteUEP)
InBlock.gif        chatDone.WaitOne(
10000True)
InBlock.gif        
If testChat = True Then
InBlock.gif            testChat 
= False
InBlock.gif            
Exit Sub
InBlock.gif        
End If
InBlock.gif
InBlock.gif        testHold 
= False
InBlock.gif        
While testHold <> True
InBlock.gif            Console.WriteLine(
"打洞ingdot.gif..")
InBlock.gif            holdDone 
= New ManualResetEvent(False)
InBlock.gif            ClientSocket.SendTo(holdbytes, remoteUEP)
InBlock.gif            ClientSocket.SendTo(holdbytes, ServerEP)
InBlock.gif            holdDone.WaitOne(
10000True)
InBlock.gif            
If testHold = True Then
InBlock.gif                
Exit While
InBlock.gif            
Else
InBlock.gif                Console.WriteLine(
"打洞超时,发送消息失败.")
InBlock.gif                Console.Write(
"是否重试,按Y重试,按任意值结束发送:")
InBlock.gif                
Dim YorN As String = Console.ReadLine().ToUpper
InBlock.gif                
If YorN = "Y" Then
InBlock.gif                    testHold 
= False
InBlock.gif                
Else
InBlock.gif                    
Exit Sub
InBlock.gif                
End If
InBlock.gif            
End If
InBlock.gif        
End While
InBlock.gif
InBlock.gif        
While testChat <> True
InBlock.gif            Console.WriteLine(
"打洞成功,正在准备发送dot.gif..")
InBlock.gif            chatDone 
= New ManualResetEvent(False)
InBlock.gif            ClientSocket.SendTo(msgbytes, remoteUEP)
InBlock.gif            chatDone.WaitOne(
10000True)
InBlock.gif            
If testChat = True Then
InBlock.gif                Console.WriteLine(
"消息发送成功!!")
InBlock.gif                
Exit While
InBlock.gif            
Else
InBlock.gif                Console.WriteLine(
"发送超时,发送消息失败.")
InBlock.gif                Console.Write(
"是否重试,按Y重试,按任意值结束发送:")
InBlock.gif                
Dim YorN As String = Console.ReadLine().ToUpper
InBlock.gif                
If YorN = "Y" Then
InBlock.gif                    testChat 
= False
InBlock.gif                
Else
InBlock.gif                    
Exit Sub
InBlock.gif                
End If
InBlock.gif            
End If
InBlock.gif        
End While
InBlock.gif        testHold 
= False
InBlock.gif        testChat 
= False
ExpandedSubBlockEnd.gif    
End Sub

InBlock.gif
InBlock.gif    
'处理聊天消息
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Private Sub showChatMsg()Sub showChatMsg(ByVal indata() As ByteByVal recvcount As Integer)
InBlock.gif        
Dim msgStr As String = Encoding.Unicode.GetString(indata, 4, recvcount - 4)
InBlock.gif        
Dim splitStr() As String = msgStr.Split("|")
InBlock.gif        
Dim fromUname As String = splitStr(0)
InBlock.gif        
Dim msg As String = splitStr(1)
InBlock.gif        Console.WriteLine(
Chr(10& Chr(13& "收到来自" & fromUname & "的消息:" & msg)
InBlock.gif        Console.Write(
"Client>")
InBlock.gif        
Dim i As Integer
InBlock.gif        
For i = 0 To OLUserName.Length - 1
InBlock.gif            
If OLUserName(i) = fromUname Then
InBlock.gif                
Exit For
InBlock.gif            
End If
InBlock.gif        
Next
InBlock.gif        
Dim tempbytes() As Byte = Encoding.Unicode.GetBytes(CHTMSGEND)
InBlock.gif        ClientSocket.SendTo(tempbytes, OLUserEP(i))
ExpandedSubBlockEnd.gif    
End Sub

InBlock.gif
InBlock.gif    
'处理打洞函数
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Private Sub makeHold()Sub makeHold(ByVal indata() As ByteByVal recvcount As Integer)
InBlock.gif        
Dim makholdstr As String = Encoding.Unicode.GetString(indata, 4, recvcount)
InBlock.gif        
Dim ipepstr() As String = makholdstr.Split(":")
InBlock.gif        
Dim holdEP As IPEndPoint = New IPEndPoint(IPAddress.Parse(ipepstr(0)), ipepstr(1))
InBlock.gif
InBlock.gif        
Dim holdbytes() As Byte = Encoding.Unicode.GetBytes(HOLDOK & username)
InBlock.gif        ClientSocket.SendTo(holdbytes, holdEP)
InBlock.gif        Console.WriteLine(
"回送打洞消息.")
ExpandedSubBlockEnd.gif    
End Sub

InBlock.gif
InBlock.gif    
'处理用户上线的函数
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Private Sub addOnLine()Sub addOnLine(ByVal inData() As ByteByVal recvCount As Integer)
InBlock.gif        
Dim inStr As String = Encoding.Unicode.GetString(inData, 4, recvCount - 4)
InBlock.gif        
Dim userinfo() As String = inStr.Split("|")
InBlock.gif        
Dim strUserEP() As String = userinfo(1).Split(":")
InBlock.gif
InBlock.gif        
Dim i As Integer
InBlock.gif        
For i = 0 To OLUserName.Length - 1
InBlock.gif            
If OLUserName(i) = "" Then
InBlock.gif                OLUserName(i) 
= userinfo(0)
InBlock.gif                OLUserEP(i) 
= New IPEndPoint(IPAddress.Parse(strUserEP(0)), strUserEP(1))
InBlock.gif                Console.WriteLine(
Chr(10& Chr(13& "用户" & OLUserName(i) & "上线了. 用户地址:" & OLUserEP(i).ToString)
InBlock.gif                Console.Write(
"Client>")
InBlock.gif                
Exit Sub
InBlock.gif            
End If
InBlock.gif        
Next
InBlock.gif
InBlock.gif        
ReDim Preserve OLUserName(i + 1)
InBlock.gif        
ReDim Preserve OLUserEP(i + 1)
InBlock.gif
InBlock.gif        OLUserName(i 
+ 1= userinfo(0)
InBlock.gif        OLUserEP(i 
+ 1= New IPEndPoint(IPAddress.Parse(strUserEP(0)), strUserEP(1))
InBlock.gif
InBlock.gif        Console.WriteLine(
Chr(10& Chr(13& "用户" & OLUserName(i + 1& "上线了. 用户地址:" & OLUserEP(i + 1).ToString)
InBlock.gif        Console.Write(
"Client>")
InBlock.gif
ExpandedSubBlockEnd.gif    
End Sub

InBlock.gif
InBlock.gif    
'处理用户下线的函数
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Private Sub removeOnLine()Sub removeOnLine(ByVal inData() As ByteByVal recvCount As Integer)
InBlock.gif        
Dim offUname As String = Encoding.Unicode.GetString(inData, 4, recvCount - 4)
InBlock.gif
InBlock.gif        
Dim i As Integer
InBlock.gif        
For i = 0 To OLUserName.Length - 1
InBlock.gif            
If OLUserName(i) = offUname Then
InBlock.gif                OLUserName(i) 
= ""
InBlock.gif                OLUserEP(i) 
= Nothing
InBlock.gif                Console.WriteLine(
Chr(10& Chr(13& "用户" & offUname & "下线了.")
InBlock.gif                Console.Write(
"Client>")
InBlock.gif                
Exit For
InBlock.gif
InBlock.gif            
End If
InBlock.gif        
Next
InBlock.gif        
Dim j As Integer
InBlock.gif        
For j = 0 To OLUserName.Length - 1
InBlock.gif            
If OLUserName(j) <> "" Then
InBlock.gif                Console.WriteLine(OLUserName(j))
InBlock.gif                Console.Write(
"Client>")
InBlock.gif            
End If
InBlock.gif
InBlock.gif
InBlock.gif        
Next
ExpandedSubBlockEnd.gif    
End Sub

InBlock.gif
InBlock.gif    
'发送消息的函数
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Public Function sendmsg()Function sendmsg(ByVal msg As StringByVal sendToIPEP As IPEndPoint) As String
InBlock.gif
InBlock.gif        
Dim sendBytes As [Byte]() = Encoding.Unicode.GetBytes(msg)
InBlock.gif
InBlock.gif        
'判断发送的字节数是否超过了服务器缓冲区大小
InBlock.gif
        If sendBytes.Length > 1024 Then
InBlock.gif            
Return "W输入的字数太多"
InBlock.gif        
End If
InBlock.gif
InBlock.gif        
'判断消息是否发送成功
InBlock.gif
        While msgSendEnd = False
InBlock.gif
InBlock.gif            sendDone 
= New ManualResetEvent(False)
InBlock.gif
InBlock.gif            
Try
InBlock.gif
InBlock.gif                ClientSocket.SendTo(sendBytes, sendToIPEP)
InBlock.gif
InBlock.gif                sendDone.WaitOne(
10000True'阻塞线程10秒
InBlock.gif

InBlock.gif                
If msgSendEnd = False Then
InBlock.gif                    Console.WriteLine(
"消息发送超时")
InBlock.gif                
Else
InBlock.gif                    
Exit While
InBlock.gif                
End If
InBlock.gif
InBlock.gif            
Catch e As Exception
InBlock.gif
InBlock.gif                Console.WriteLine(
"发送消息失败" & e.ToString)
InBlock.gif                
Exit Function
InBlock.gif
InBlock.gif            
End Try
InBlock.gif
InBlock.gif            Console.Write(
"是否重试?按Y重试,按任意键退出:")
InBlock.gif            
Dim userInput As String = Console.ReadLine.ToUpper
InBlock.gif
InBlock.gif            
If userInput = "Y" Then
InBlock.gif            
Else
InBlock.gif                msgSendEnd 
= False
InBlock.gif                
Exit Function
InBlock.gif            
End If
InBlock.gif
InBlock.gif        
End While
InBlock.gif
InBlock.gif        msgSendEnd 
= False
InBlock.gif
ExpandedSubBlockEnd.gif    
End Function

InBlock.gif
InBlock.gif    
'用保持在线状态的函数
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Private Sub holdonline()Sub holdonline(ByVal state As [Object])
InBlock.gif        ClientSocket.SendTo(holdBytes, ServerEP)
ExpandedSubBlockEnd.gif    
End Sub

InBlock.gif
ExpandedSubBlockEnd.gif
#End Region

InBlock.gif
ExpandedBlockEnd.gif
End Module

None.gif

这段代码已经基本实现udp打洞的效果,希望对初学者有所帮助.

转载于:https://www.cnblogs.com/yrh2847189/archive/2007/06/20/790013.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值