全面展示VB.NET服務(wù)器端
VB.NET還是比較常用的,于是我研究了一下VB.NET服務(wù)器端,在這里拿出來和大家分享一下,希望對(duì)大家有用。
這是用VB.NET實(shí)現(xiàn)的一個(gè)簡(jiǎn)單的P2P示例,利用了UDP打洞技術(shù).分服務(wù)器端跟客戶端,VB.NET服務(wù)器端負(fù)責(zé)登陸記錄用戶的IP和端口及轉(zhuǎn)發(fā)打洞消息(相關(guān)技術(shù)在CSDN搜一下,有很多的),原理到處都有,這里貼出了VB.NET的代碼,供初學(xué)者交流,也歡迎高手點(diǎn)評(píng)。
VB.NET服務(wù)器端在啟動(dòng)成功后,輸入help可以查看到服務(wù)器相關(guān)命令??蛻舳嗽诘顷懗晒?,輸入help可以查看客戶端相關(guān)命令。(登陸時(shí)用戶名隨便)
以下是VB.NET服務(wù)器端:
- Imports System.Net
- Imports System.Net.Sockets
- Imports System.Text
- Imports System.Threading
- Imports System.Collections
- Module myUDPServer
- #Region "全局變量"
- Dim ServerSocket As New Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
- Dim ipep As IPEndPoint = New IPEndPoint(IPAddress.Any, 11000)
- Dim htUserList As New Hashtable '用來保存在線用戶和用戶的"IP和端口"
- Dim userName(0) As String
- Dim userIPEP(0) As IPEndPoint
- Dim userTime(0) As Integer
- Dim timerDelegate As New TimerCallback(AddressOf onLineTimeOut)
- #End Region
- #Region "參數(shù)"
- '以下是客戶端到服務(wù)器端的消息開頭
- Const LOGININ As String = "10" '請(qǐng)求登陸的消息|||消息形式:10+自己的用戶名
- Const LOGINOUT As String = "11" '請(qǐng)求登出的消息|||消息形式:11+自己的用戶名
- Const GETULIST As String = "12" '請(qǐng)求獲得在線用戶列表|||消息形式:12
- Const P2PCONN As String = "13" '請(qǐng)求P2P連接的消息|||消息形式:13+自己的用戶名+|+對(duì)方的用戶名
- Const HOLDLINE As String = "14" '保持連接.|||消息開式:14+自己的用戶名
- '以下是服務(wù)器到客戶端的消息開頭
- Const HVUSER As String = "20" '用戶名已存在
- Const GETUSER As String = "21" '在線用戶列表|||消息格式:21+用戶名+EP
- Const MAKHOLD As String = "22" '打洞命令|||消息格式:22+IP
- Const LOGINOK As String = "23" '登陸成功
- Const SERVCLS As String = "24" '服務(wù)器關(guān)閉
- Const MSGEND As String = "25" '消息結(jié)束
- '以下是服務(wù)器端的命名
- Const EXITPRO As String = "EXIT" '退出命令
- Const SHOWULIST As String = "SHOWUSER" '顯示在線用戶
- Const HELP As String = "HELP" '顯示幫助
- #End Region
- #Region "方法"
- '主函數(shù),程序入口
- Sub Main()
- '獲得服務(wù)器的IP地址
- Dim addressList As System.Net.IPAddress() = Dns.GetHostByName(Dns.GetHostName()).AddressList
- Dim ServerIP As IPAddress = addressList(0)
- ServerSocket.Bind(ipep)
- Console.WriteLine("服務(wù)器正在啟動(dòng)....")
- Console.WriteLine("服務(wù)器IP:" & ServerIP.ToString & " 正在監(jiān)聽" & ipep.Port.ToString & "端口")
- Dim listenTH As New Thread(AddressOf listen)
- listenTH.Start() '啟用監(jiān)聽的線程
- Console.WriteLine("服務(wù)器啟動(dòng)成功.....")
- Dim timer As New Timer(timerDelegate, Nothing, 0, 5000)
- Dim SVInput As String
- While True
- Console.Write("Server>")
- SVInput = Console.ReadLine().ToUpper
- Select Case SVInput
- Case EXITPRO
- listenTH.Abort()
- ServerSocket.Close()
- Exit Sub
- Case SHOWULIST
- showUser()
- Case HELP
- Console.Write("*" & Chr(10) & Chr(13) & "exit:輸出當(dāng)前程序" & Chr(10) & Chr(13) &
"showuser:顯示當(dāng)前在線用戶例表" & Chr(10) & Chr(13) &
"help:顯示幫助" & Chr(10) & Chr(13) & "*" & Chr(10) & Chr(13))- Case Else
- Console.WriteLine("*" & Chr(10) & Chr(13)
& "笨瓜,你輸入的不是有效的命令." & Chr(10) & Chr(13) & "*")- End Select
- End While
- End Sub
【編輯推薦】