P2P的简单示例(VB.net版) 二__教程 |
|
日期:2007-5-20 0:37:32 人气:100 [大 中 小] |
|
|
|
以下是客户端: Imports System.Net Imports System.Net.Sockets Imports System.Text Imports System.Threading
Module Module1
#Region "参数"
'以下是客户端到服务器端的消息开头 Const LOGININ As String = "10" '请求登陆的消息|||消息形式:10+自己的用户名 Const LOGINOUT As String = "11" '请求登出的消息|||消息形式:11+自己的用户名 Const GETULIST As String = "12" '请求获得在线用户列表|||消息形式:12+自己的用户名 Const P2PCONN As String = "13" '请求P2P连接的消息|||消息形式:13+自己的用户名+对方的用户名 Const HOLDLINE As String = "14" '保持连接.|||消息开式:14+自己的用户名
'以下是服务器到客户端的消息开头 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" '服务器关闭 Const MSGEND As String = "25" '消息结束
'以下是客户端到客户端的消息开头 Const HOLDOK As String = "30" '打洞成功 Const CHATMSG As String = "31" '聊天消息 Const CHTMSGEND As String = "32" '聊天消息发送成功
'以下是客户端的命名 Const EXITPRO As String = "EXIT" '退出命令 Const SHOWULIST As String = "SHOWUSER" '显示在线用户 Const HELP As String = "HELP" '显示帮助 Const SEND As String = "SEND" '发送消息
#End Region
#Region "全局全量"
Delegate Sub myMethodDelegate(ByRef myInData As Byte()) '登陆时用的事件
'Dim MaxTry As Integer = 5 Dim msgSendEnd As Boolean = False '消息是否发送成功,若发送成功,则会返回结束消息 Dim ThListen As New Thread(AddressOf listen) '监听的线程 Dim ClientSocket As New Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp) '客户端套节字的定义 Dim username As String '当前用户名 Dim ServerEP As IPEndPoint '服务器的IPEP Dim holdBytes As [Byte]() = Encoding.Unicode.GetBytes(HOLDLINE & username) '和服务器保持连接连接时用到的byte数组 Dim OLUserName() As String Dim OLUserEP() As IPEndPoint Dim getUrecCount As Integer Dim testHold As Boolean = False Dim testChat As Boolean = False
Private receiveDone As ManualResetEvent '在登陆时用来阻塞线程,等待收到数据 Private sendDone As ManualResetEvent '用来阴塞发送消息的线程.等待收到回送的确认消息 Private getUDone As ManualResetEvent '用来阻塞请求好友名单的线程,等待接收好友名单 Private holdDone As ManualResetEvent '用来阻塞打洞时的线程 Private chatDone As ManualResetEvent '用来阻塞发送聊天消息时的线程
Dim timerDelegate As New TimerCallback(AddressOf holdonline) '为保持在线状态弄得
#End Region
#Region "方法"
'主函数,程序入口 Sub Main() Dim InputIP As String Dim InputOK As Boolean = False
'判断输入的IP,并且保存服务器的IPEP While InputOK <> True Console.Write("请输入服务器IP:") InputIP = Console.ReadLine() Try ServerEP = New IPEndPoint(IPAddress.Parse(InputIP), 11000) InputOK = True Catch Console.WriteLine("你输入的服务器IP不正确,请重新输入.") InputOK = False End Try End While
Dim bool As Boolean = False
'判断用户是否登陆成功 While bool <> True
Dim LoginOK As Boolean = Login() If LoginOK = True Then bool = True Else Console.Write("是否重试:输入Y重试,输入任意值退出程序:") Dim tempYN As String = Console.ReadLine.ToUpper If tempYN = "Y" Then bool = False Else |
|
出处:本站原创 作者:佚名 |
|
|