使用VB.net写一个UDP通信的窗口程序
时间: 2023-12-10 19:05:36 浏览: 171
好的,下面是一个简单的VB.net UDP通信窗口程序示例:
```vb
Imports System.Net.Sockets
Imports System.Text
Public Class Form1
Private udpClient As UdpClient
Private udpReceiveThread As Threading.Thread
Private receiveBytes As Byte()
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
udpClient = New UdpClient(1234)
udpReceiveThread = New Threading.Thread(AddressOf ReceiveData)
udpReceiveThread.Start()
End Sub
Private Sub ReceiveData()
While True
receiveBytes = udpClient.Receive(New IPEndPoint(IPAddress.Any, 0))
Dim receiveString As String = Encoding.ASCII.GetString(receiveBytes)
Me.Invoke(Sub() TextBox1.AppendText("Received: " & receiveString & vbCrLf))
End While
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sendBytes As Byte() = Encoding.ASCII.GetBytes(TextBox2.Text)
udpClient.Send(sendBytes, sendBytes.Length, "127.0.0.1", 1234)
TextBox1.AppendText("Sent: " & TextBox2.Text & vbCrLf)
TextBox2.Clear()
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
udpReceiveThread.Abort()
udpClient.Close()
End Sub
End Class
```
在这个程序中,我们创建了一个UDP客户端,并在窗口加载时启动了一个接收数据的线程。当用户点击按钮时,程序会将用户输入的文本转换为字节流并通过UDP发送到指定的IP地址和端口。同时,在接收线程中不断接收来自任意IP地址和端口的数据,并在文本框中显示接收到的数据。在窗口关闭时,我们需要关闭接收线程和UDP客户端。
阅读全文