摘要:[VB.NET] 簡單UDP連線程式
因為學校的資訊網路課程要寫一個TCP或UDP的連線程式,所以就找了網路上的範例來修改。
我根據UdpClient 類別裡面的範例,寫了Server/Client的程式,功能很簡單,Client傳送名字,Server會回傳「早上好, 名字」。
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Module Module1
Sub Main()
Dim port As Integer = 12345
Dim udpClient As New UdpClient()
Try
udpClient.Connect("localhost", port)
Console.Write("請輸入你的名字: ")
Dim inputString As String = Console.ReadLine()
Dim sendBytes As [Byte]() = Encoding.UTF8.GetBytes(inputString)
udpClient.Send(sendBytes, sendBytes.Length)
Dim receiveBytes As [Byte]() = udpClient.Receive(udpClient.Client.LocalEndPoint)
Dim returnData As String = Encoding.UTF8.GetString(receiveBytes)
Console.WriteLine(returnData.ToString())
udpClient.Close()
Catch e As Exception
Console.WriteLine(e.ToString())
End Try
Console.ReadKey()
End Sub
End Module
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Module Module1
Sub Main()
Dim port As Integer = 12345
Dim udpClient As New UdpClient(port)
Try
Dim RemoteIpEndPoint As New IPEndPoint(IPAddress.Any, port)
While (True)
Dim receiveBytes As [Byte]() = udpClient.Receive(RemoteIpEndPoint)
Dim receiveData As String = Encoding.UTF8.GetString(receiveBytes)
Console.WriteLine("收到資料: " & receiveData)
Console.WriteLine("來自" & RemoteIpEndPoint.Address.ToString() & ":" & RemoteIpEndPoint.Port)
Dim sendData As String = "早上好, " & receiveData
Dim sendBytes As [Byte]() = Encoding.UTF8.GetBytes(sendData)
udpClient.Send(sendBytes, sendBytes.Length, RemoteIpEndPoint)
Console.WriteLine("傳回資料: " & sendData)
Console.WriteLine()
End While
udpClient.Close()
Catch e As Exception
Console.WriteLine(e.ToString())
End Try
End Sub
End Module
專案下載(VB2012): [VB.NET] 簡單UDP連線程式.zip
文章內容僅提供技術分享,如有錯誤還請不吝指教。