Visual Basic UDPClient服务器/客户端模型?

3
我正在尝试制作一个非常简单的系统,用于从客户端向服务器发送消息(稍后也可以从服务器向客户端发送消息,但首先是基础)。我不确定如何使用UDPClient发送和接收消息(特别是接收消息),主要是因为我没有任何触发ReceiveMessage()函数的东西,也不确定会有什么触发。源代码在此链接中,转到文件>下载。如果您只想运行exe,则已经构建完成。所以我的问题基本上是:我如何轻松地使用UDPClient,如何使此系统工作,并执行此类连接的一些提示?我应该注意什么(线程,代码问题等)?

你需要使用UDP吗?你看过AMPQ了吗?试试访问http://www.rabbitmq.com。 - Ryan Gunn
1
谷歌是你的朋友,我认为在发帖提问之前,你应该先尝试查找研究资料。我之前的帖子是为了向你展示消息传递的其他替代方案。祝你好运! - Ryan Gunn
我在这里提问是有原因的,因为我在谷歌搜索时没有找到适用的结果,而我找到的结果存在问题或对我来说效果不佳。 - Postman
2个回答

6
你需要先设置两个UdpClient,一个用于监听,另一个用于发送数据。(你还需要选择一个空闲的端口号,并知道目标的IP地址 - 你想要向其发送数据的机器。)
为了设置接收方:
  1. 使用之前选择的端口号实例化你的UdpClient变量,

  2. 创建一个新线程来避免在接收数据时阻塞,

  3. 循环使用客户端的接收方法,只要你想接收数据(循环执行应该在新线程中),

  4. 当你收到一组数据(称为“数据包”)时,你可能需要将字节数组转换为更有意义的内容,

  5. 创建一个退出循环的方法,当你想结束接收数据时使用。

为了设置发送方:
  1. 使用之前选择的端口号实例化你的 UdpClient 变量(你可能需要启用发送广播数据包的功能。这允许你向你的局域网上的所有监听器发送数据),

  2. 当你需要传输数据时,将数据转换为字节数组,然后调用 Send()

我建议你快速浏览一下this

以下是一些代码,可以帮助你入门...

'''''''''''''''''''''''Set up variables''''''''''''''''''''
Private Const port As Integer = 9653                         'Port number to send/recieve data on
Private Const broadcastAddress As String = "255.255.255.255" 'Sends data to all LOCAL listening clients, to send data over WAN you'll need to enter a public (external) IP address of the other client
Private receivingClient As UdpClient                         'Client for handling incoming data
Private sendingClient As UdpClient                           'Client for sending data
Private receivingThread As Thread                            'Create a separate thread to listen for incoming data, helps to prevent the form from freezing up
Private closing As Boolean = False                           'Used to close clients if form is closing

''''''''''''''''''''Initialize listening & sending subs'''''''''''''''''

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load
    InitializeSender()          'Initializes startup of sender client
    InitializeReceiver()        'Starts listening for incoming data                                             
End Sub

''''''''''''''''''''Setup sender client'''''''''''''''''

Private Sub InitializeSender()
    sendingClient = New UdpClient(broadcastAddress, port)
    sendingClient.EnableBroadcast = True
End Sub

'''''''''''''''''''''Setup receiving client'''''''''''''

Private Sub InitializeReceiver()
    receivingClient = New UdpClient(port)
    Dim start As ThreadStart = New ThreadStart(AddressOf Receiver)
    receivingThread = New Thread(start)                            
    receivingThread.IsBackground = True                            
    receivingThread.Start()                                       
End Sub

'''''''''''''''''''Send data if send button is clicked'''''''''''''''''''

Private Sub sendBut_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles sendBut.Click
    Dim toSend As String = tbSend.Text                  'tbSend is a textbox, replace it with whatever you want to send as a string
    Dim data() As Byte = Encoding.ASCII.GetBytes(toSend)'Convert string to bytes
    sendingClient.Send(data, data.Length)               'Send bytes
End Sub

'''''''''''''''''''''Start receiving loop''''''''''''''''''''''' 

Private Sub Receiver()
    Dim endPoint As IPEndPoint = New IPEndPoint(IPAddress.Any, port) 'Listen for incoming data from any IP address on the specified port (I personally select 9653)
    While (True)                                                     'Setup an infinite loop
        Dim data() As Byte                                           'Buffer for storing incoming bytes
        data = receivingClient.Receive(endPoint)                     'Receive incoming bytes 
        Dim message As String = Encoding.ASCII.GetString(data)       'Convert bytes back to string
        If closing = True Then                                       'Exit sub if form is closing
            Exit Sub
        End If
    End While
End Sub

'''''''''''''''''''Close clients if form closes''''''''''''''''''

Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
    closing = True          'Tells receiving loop to close
    receivingClient.Close()
    sendingClient.Close()
End Sub

这里还有几个例子:这里, 这里, 这里这里

0
Imports System.Threading

Shared client As UdpClient
Shared receivePoint As IPEndPoint

client = New UdpClient(2828) 'Port
receivePoint = New IPEndPoint(New IPAddress(0), 0)

Dim readThread As Thread = New Thread(New ThreadStart(AddressOf WaitForPackets))
readThread.Start()

Public Shared Sub WaitForPackets()
    While True
        Dim data As Byte() = client.Receive(receivePoint)
        Console.WriteLine("=" + System.Text.Encoding.ASCII.GetString(data))
    End While
End Sub

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接