2011-01-29 35 views
1

嘿所有我想讓這個代碼在VB6中工作就好,在VB.net 2008工作。它似乎並不想連接(但沒有錯誤後,它通過了sockMain.Connect()Winsock在VB.net不工作

sockMain.RemoteHost = "192.168.1.77" 
sockMain.RemotePort = 77 
sockMain.Connect() 

現在,當我這樣做:。

On Error GoTo oops 
    sockMain.SendData(txtSend.Text) 

oops: 
    If Err.Number = 40006 Then 
     MsgBox("It doesnt seem that the server is running. Please check it and try again") 
    End If 

我得到它似乎正在運行的服務器,請檢查並再試一次錯誤

我在想什麼?

大衛

+0

你首先想到的是VB 6和VB.NET完全是不同的語言,只有一些表面上相似的語法。也就是說,`On Error GoTo`在VB.NET中比*棄用更多*,因爲現在可以使用結構化的異常處理(`try` /`catch`)。獲取一本好書,不僅要學習.NET習語,還要學習一般的面向對象編程。從長遠來看,你會爲自己做一件大好事,因爲你從VB 6到VB.NET的重寫實際上是值得的。 – 2011-01-29 05:46:37

回答

4

正如我在評論解釋,VB.NET和VB 6幾乎完全不同的編程語言。通過嘗試在VB.NET中編寫VB 6代碼,你沒有做任何好處。如果您不打算利用.NET平臺提供的新功能,則根本沒有理由進行遷移。

除了我已經提到的結構化異常處理之外,您應該拋棄舊的WinSock控件,轉而使用System.Net.Sockets namespace中的類。

嘗試更換你所擁有的東西,如下面的代碼:

Dim tcpClient As New System.Net.Sockets.TcpClient() 
tcpClient.Connect("192.168.1.77", 77) 
Dim networkStream As NetworkStream = tcpClient.GetStream() 
If networkStream.CanWrite And networkStream.CanRead Then 
    ' Do a simple write. 
    Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("Is anybody there") 
    networkStream.Write(sendBytes, 0, sendBytes.Length) 

    ' Read the NetworkStream into a byte buffer. 
    Dim bytes(tcpClient.ReceiveBufferSize) As Byte 
    networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize)) 

    ' Output the data received from the host to the console. 
    Dim returnData As String = Encoding.ASCII.GetString(bytes) 
    Console.WriteLine(("Host returned: " + returnData)) 
Else 
    If Not networkStream.CanRead Then 
     Console.WriteLine("Cannot not write data to this stream. " & 
          "Please check the server and try again.") 
     tcpClient.Close() 
    Else 
     If Not networkStream.CanWrite Then 
      Console.WriteLine("Cannot read data from this stream. " & 
           "Please check the server and try again.") 
      tcpClient.Close() 
     End If 
    End If 
End If 
0

連接調用可能需要一點時間才能完成。即使您的客戶端與服務器建立了物理連接,您也必須花一點時間建立TCP虛擬電路。如果您在SendData調用中放置斷點並等待一兩秒鐘,然後繼續,您可能會發現它工作正常。

1

如果你想在.NET世界VB6的Winsock的感覺試試this,當心它沒有更新自2008年有幾個BUG,看評論在acticle的末尾介紹