VB.Net TcpClient错误 - 请求的地址在其上下文中无效

时间:2014-11-13 13:09:26

标签: vb.net tcpclient

我正在尝试实现TcpClient并不断收到错误

  

请求的地址在其上下文中无效

但是,只有将代码放在主窗体调用的类中时才会发生这种情况。当我将代码放在主窗体中时(在窗体加载事件中),不会发生错误,并且TcpClient上的通信成功。

我试图使用Inherits ApplicationContext来装饰该类,但仍然会抛出错误。下面是我正在使用的代码:

  1. 班级

    Public Class dasharClient
    
       Inherits ApplicationContext
    
        Public port As Integer
        Public hostname As String
        Private myClient As TcpClient
        Sub New()
            myClient = New TcpClient(hostname, port)
            Dim subscribe As Byte() = Encoding.ASCII.GetBytes("Hello World")
            myClient.GetStream.BeginWrite(subscribe, 0, subscribe.Length, AddressOf MyWriteCallBack, myClient.GetStream)
        End Sub
        Public Sub MyWriteCallBack(ByVal ar As IAsyncResult)
            CType(ar.AsyncState, NetworkStream).EndWrite(ar)
       End Sub
    End Class
    
  2. 我从主窗体初始化类

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    
        Dim testClass As New dasharClient With {.port = 3354, .hostname = "my.domain.com"}
    
    End Sub
    
  3. 如上所述,如果我将类中的代码放入表单load event sub(没有类装饰),它就可以工作!

0 个答案:

没有答案