0
我試圖編寫一個小的異步套接字庫,我可以用它來創建客戶端/服務器應用程序。如果我將它放在表單中,我可以讓所有的代碼運行良好,但是如果我嘗試將它移出到它自己的類中,我無法弄清楚如何使用連接狀態更新表單等。下面是代碼,縮短了一點,以便更容易閱讀和輸入。異步套接字庫不更新形式
表格代號:
Class Form1
Dim Network as NetworkModule
Public Sub Button1_Click(Sender, e) Handles Button1.Click
Network = New NetworkModule("127.0.0.1", 1234)
End Sub
End Class 'Form1
NetworkModule類:
Class NetworkModule
Private mSocket as Socket
Public Sub New(IP as string, Port as Integer)
Dim remoteEP as New IPEndpoint(IP.Parse(IP), Port)
mSocket = New Socket(internetwork, stream, tcp)
mSocket.BeginConnect(remoteEP, New AsyncCallback(AddressOf onConnect), mSocket)
Notify("Connection to " & remoteEP.ToString) 'This one works
End Sub 'New
Private Sub onConnect(ar as IAsyncResult)
mSocket = CType(ar.AsyncState, Socket)
mSocket.EndConnect(ar)
Notify("Connected") 'This one never shows
End Sub 'onConnect
Private Delegate Sub _Notify(Msg as String)
Private Sub Notify(Msg as String)
If Form1.txtLog.InvokeRequired Then
Form1.txtLog.Invoke(New _Notify(AddressOf Notify), Msg)
Exit Sub
End if
Form1.txtLog.Text &= Msg & vbcrlf
End Sub 'Notify
End Class 'NetworkModule
有其實更多的那類,但是第一個消息出去後,我從來沒有得到任何東西。我不確定該從哪裏出發。我嘗試了很多我在谷歌搜索中找到的不同方法,其中一些來自這裏,一些不是。任何人有任何想法?
好吧,這實現會給我一個InvalidOperationException錯誤,並說在創建窗口句柄之前,Invoke或BeginInvoke無法在控件上調用。從我讀過的內容來看,如果句柄沒有創建,'InvokeRequired'將永遠是錯誤的,所以我甚至沒有嘗試修改它,似乎毫無意義。有什麼想法嗎? – Timbermar
我嘗試將'NotifyDelegate = New NetworkMod ...'行從'New()'移動到'Form_Load()',相同的結果與相同的錯誤消息。將Form1.Invoke(...'行改爲'Form1.txtLog.Invoke(...') – Timbermar
我假設你有一個全局變量掛在某處指向Form1的地方,但這可能沒有我已經通過修改代碼糾正了這個假設,以便調用形式在構造函數中傳遞給NetworkModule並作爲模塊級成員存儲在NetworkModule中。實際上,不應該傳遞表單類型;接口應該被創建並通過,但是你需要在清理之前獲得基本實現的功能 –