本实例说明了在 .NET 下利于 UDP 协议发送和接受消息。实现这个目的,主要是利用 UDPClient 类的 Send 方法和 Receive 方法。
以下程序包括一个接受消息的过程和发送消息的过程。由于是同步接受,所以在对方消息没发送过来之前,接受过程将会一直阻塞程序的执行。
因此,为接受过程新开辟了一个线程。程序代码如下:
Imports System
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Imports System.Text
Public Class UDPChat
Public Shared Sub Main()
Dim temp As New UdpChat
Console.ReadLine()
End Sub
Private remoteIP As IPAddress
Private localPort As Integer
Private remotePort As Integer
Public Sub New()
Console.WriteLine("请输入对方 IP:")
remoteIP = IPAddress.Parse(Console.ReadLine())
Console.WriteLine("请输入对方 端口:")
remotePort = Int32.Parse(Console.ReadLine())
Console.WriteLine("请输入本地 端口:")
localPort = Int32.Parse(Console.ReadLine())
Dim t As New Thread(New ThreadStart(AddressOf Receive))
t.Start()
While True
SendData(Console.ReadLine())
End While
End Sub
Public Sub SendData(ByVal Msg As String)
Dim sender As New UdpClient
Dim remoteEP As New IPEndPoint(remoteIP, remotePort)
sender.Connect(remoteEP)
Dim sendByte() As Byte = Encoding.ASCII.GetBytes(Msg)
sender.Send(sendByte, sendByte.Length)
End Sub
Public Sub Receive()
Console.WriteLine("********** 现在开始聊天 **********")
Dim receiver As New UdpClient(localPort)
Dim localEP As IPEndPoint = Nothing
Dim receData(1024) As Byte
While True
receData = receiver.Receive(localEP)
Console.WriteLine("-"c & Encoding.ASCII.GetString(receData))
End While
End Sub
End Class