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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16160550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 13:21:45  来源:igfitidea点击:

Visual Basic UDPClient Server/Client model?

vb.netclient-serverchatudpclient

提问by Postman

So I'm trying to make a very simple system to send messages from a client to a server (and later on from server to client as well, but baby steps first). I'm not sure exactly how to use UDPClient to send and receive messages (especially to receive them), mostly because I don't have anything triggering the ReceiveMessage()function and I'm not sure what would.

所以我正在尝试制作一个非常简单的系统来从客户端向服务器发送消息(稍后也从服务器到客户端,但首先是婴儿步骤)。我不确定如何使用 UDPClient 发送和接收消息(尤其是接收消息),主要是因为我没有任何东西可以触发该ReceiveMessage()功能,而且我不确定会发生什么。

Source Code is at this link, go to File>Download. It is already built if you want to just run the exe.

源代码位于此链接,转到文件>下载。如果您只想运行 exe,它已经构建好了。

So my question is basically: How can I easily use UDPClient, how can I get this system to work and what are some tips for executing this kind of connection? Anything I should watch out for (threading, issues with code,etc)?

所以我的问题基本上是:我怎样才能轻松使用UDPClient,我怎样才能让这个系统工作,以及执行这种连接的一些技巧是什么?我应该注意什么(线程、代码问题等)?

Source.

来源

回答by Sam

You need first need to set up two UdpClients. One client for listening and the other for sending data. (You'll also need to pick a free/unusedport number and know the IP address of your target - the machine you want to senddata to.)

您首先需要设置两个UdpClients。一个客户端用于监听,另一个用于发送数据。(您还需要选择一个空闲/未使用的端口号并知道目标的 IP 地址 - 您要向其发送数据的机器。)

To set up the receiver,

要设置接收器,

  1. Instantiate your UdpClientvariable with the port number you chose earlier,

  2. Create a new thread to avoid blocking while receiving data,

  3. Loop over the client's receive method for as long as you want to receive data (the loop's execution should be within the new thread),

  4. When you receive one lot of data (called a "packet") you may need to convert the byte array to something more meaningful,

  5. Create a way to exit the loop when you want to finish receiving data.

  1. UdpClient使用您之前选择的端口号实例化您的变量,

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

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

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

  5. 创建一种在您想完成接收数据时退出循环的方法。

To set up the sender,

要设置发件人,

  1. Instantiate your UdpClientvariable with the port number you chose earlier (you may want to enable the ability to send broadcast packets. This allows you to send data to all listeners on your LAN),

  2. When you need to transmit data, convert the data to a byte array and then call Send().

  1. UdpClient使用您之前选择的端口号实例化您的变量(您可能希望启用发送广播数据包的功能。这允许您将数据发送到 LAN 上的所有侦听器),

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

I'd suggest that you have a quick skim read through this.

我建议你必须通过一个快速脱脂读这个

Here's some code to get you started off...

这里有一些代码可以让你开始......

'''''''''''''''''''''''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

Here are a few other exmples: Here, here, hereand here.

这里有一些其他的例子:这里这里这里这里

回答by Arvy

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