如何创建 GUI 中所有按钮都可以使用的 TCP 连接和流?

How can I create a TCP connection and stream that can be used by all buttons in a GUI?

我正在尝试为 TCP 连接中的服务器创建 GUI。我想要一个创建连接和可能的底层流的按钮,然后有其他按钮通过这个流发送序列化命令。我 运行 遇到了问题,因为每个按钮都充当子过程,所以我相信流在范围之外并且对每个按钮都不可用。

我试过在按钮之外创建流,但下面的代码在 myServer.Start() 处抛出错误,提示未声明 myServer。

Public Class Form1

Dim myIP As IPAddress = IPAddress.Parse("my ip")
Dim myServer As New TcpListener(myIP, 800)
    myServer.Start() 'Error line

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  Stream Write Stuff
End Sub

End Class

我也试过在每次按下按钮时开始监听,但是在连接一次后 myServer.Start() 无限期暂停,同时监听未到来的连接尝试。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click      
    myServer.Start()
    Dim myClient As TcpClient = myServer.AcceptTcpClient() 
    Dim myStream As NetworkStream = myClient.GetStream
    myStream.Write(xxx)
End Sub 

如何创建一个连接和流,供我添加到 GUI 的所有按钮使用?

How can I create a connection and stream that is available to all the buttons I would add to the GUI?

Public Class Form1
    ' just declare the variables
    Private myIP As IPAddress 
    Private myServer As TcpListener
    Private myStream As NetworkStream

    Sub btnStart_Click(...
       ' create the objects when you need them
        myIP = IPAddress.Parse("my ip")
        myServer = New TcpListener(...)
        myStream = myClient.GetStream

声明对象变量和创建它的实例是两件不同的事情。你同时做这两件事:

Dim myServer As New TcpListener(...)

Dim 部分声明变量(Private | Friend | Public 也是如此)。 New关键字创建一个实例;在使用对象之前,您需要同时完成这两项工作,但不必同时完成。长格式更清楚地表明有两部分:

Dim myServer As TcpListener = New TcpListener(...)

在哪里你声明的变量决定了变量的Scope。 sub 中的任何内容都只有过程级别的范围。它不会存在于该程序之外。在顶部声明,在任何过程之外,myIPmyServermyStream 将以该形式随处可用。

声明后,您可以创建一个实例,如上所示 btnStart_Click(或表单加载等)。

还有块作用域涉及If/End IfUsing/End UsingFor Each/Next 等结构。在其中声明的变量的范围仅限于该块:

If cr IsNot Nothing Then
    Dim temp As Decimal = cr.Total
End If

lblTotal.Text = temp   ''temp' is not declared. It may be inaccessible 

最后一行将是一个错误,因为 temp 是在本地块内声明的 (Dim),所以它不存在于本地块之外。这将适用于 If/End IfUsing/End UsingFor Each/Next——基本上,任何导致缩进的内容都会创建一个本地块。

另请参阅:

Scope in Visual Basic