Question Converting Vb6 code to Vb.Net

babak

New member
Joined
Jan 3, 2011
Messages
2
Programming Experience
Beginner
Hi

I want to convert following code which is VB6 to Vb.Net.Could anybody can do it?

Private Sub Form_Load()
Winsock1.Protocol = sckUDPProtocol
Winsock1.RemoteHost = "192.168.1.100"
Winsock1.RemotePort = 6000
End Sub

Private Sub Timer_OFF_Click()
Timer1.Enabled = False
End Sub

Private Sub Timer_ON_Click()
Timer1.Enabled = True
End Sub

Private Sub Timer1_Timer()
Dim s1 As String
s1 = Chr(2) + Chr(0) + Chr(2) + Chr(49) + Chr(82) + Chr(97) + Chr$(26)
Winsock1.SendData s1
Debug.Print ("send 2 \n")
Winsock1.Close
Winsock1.Bind (6000)

End Sub

Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Dim a
Winsock1.GetData a
buffer = StrConv(a, vbUnicode)
For i = 1 To Len(buffer)
shex = shex & Hex(Asc(Mid$(buffer, i, 1))) & " "
Next i

If Trim(shex) <> "21111" Then
Winsock1.SendData Chr(2)
Winsock1.SendData Chr(0)
Winsock1.SendData Chr(2)
Winsock1.SendData Chr(50)
Winsock1.SendData Chr(147)
Winsock1.SendData Chr(163)

End If
List1.Clear
List1.AddItem shex
End Sub

Thanks
 
I want to convert following code which is VB6 to Vb.Net.Could anybody can do it?
Yes, anybody can do it, including you. The way to go is to use the .Net UdpClient class: UdpClient Class (System.Net.Sockets)
To bind to port 6000 simply use the constructor:
VB.NET:
Private udp As New System.Net.Sockets.UdpClient(6000)
The remote ip endpoint to sent to will be a IPEndPoint instance:
VB.NET:
Private remote As New Net.IPEndPoint(Net.IPAddress.Parse("192.168.1.100"), 6000)
UdpClient has Send and Receive methods, the data must be Byte array so you have to convert that to/from String. (looked like you were using Unicode)
VB.NET:
Dim data As String = "some string"
Dim buffer() As Byte = System.Text.Encoding.Unicode.GetBytes(data)
data = System.Text.Encoding.Unicode.GetString(buffer)
Now you can send and receive:
VB.NET:
udp.Send(buffer, buffer.Length, remote)
buffer = udp.Receive(Nothing)
Sending and receiving is something you may do using a Timer (like before), just add one to the form from Toolbox and configure it. UdpClient does not have a 'DataArrival' event, so using a Timer you can check the Available property and conditionally call Receive. An alternative you can explore yourself is using the async BeginReceive/EndReceive methods. Note that if you have a lot of receive traffic you should not tie up the UI thread with this.
Here is a more complete example (combining previous information) for handling the Timer Tick event:
VB.NET:
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    Dim data As String = "some string"
    Dim buffer() As Byte = System.Text.Encoding.Unicode.GetBytes(data)
    udp.Send(buffer, buffer.Length, remote)

    If udp.Available > 0 Then
        buffer = udp.Receive(Nothing)
        data = System.Text.Encoding.Unicode.GetString(buffer)

    End If
End Sub
 
Back
Top