Visual Basic UDPClient服务器/客户端模型? [英] Visual Basic UDPClient Server/Client model?

查看:167
本文介绍了Visual Basic UDPClient服务器/客户端模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在尝试构建一个非常简单的系统,以将消息从客户端发送到服务器(以及以后也从服务器发送到客户端,但是首先要执行步骤)。我不确定确切如何使用UDPClient发送和接收消息(尤其是接收消息),主要是因为我没有任何东西触发 ReceiveMessage()函数,并且我不确定会怎样。

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.

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

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

所以我的问题基本上是:如何轻松使用 UDPClient ,如何使该系统正常工作,以及执行这种连接有哪些技巧?我应该注意的任何事情(线程,代码问题等)?

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 s。一个客户端用于侦听,另一个用于发送数据。 (您还需要选择一个免费/未使用端口号,并知道目标服务器的IP地址-您要向其发送数据的计算机。)

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/unused port number and know the IP address of your target - the machine you want to send data to.)

要设置接收器,


  1. 实例化您的 UdpClient 变量以及您先前选择的端口号

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

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

Create a new thread to avoid blocking while receiving data,

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

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),

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

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

创建一种当您要完成接收数据时退出循环的方法。

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

要设置发件人


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

  1. Instantiate your UdpClient variable 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),

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

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

我建议您可以快速浏览一下

下面是一些让您入门的代码...

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, here and here.

这篇关于Visual Basic UDPClient服务器/客户端模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆