2011-01-29 33 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的末尾介绍