Winsock for VB.Net Community 2019

Member_2_241474
Member_2_241474 used Ask the Experts™
on
I had this question after viewing socket connect() & bind() together?.

I am an old VB6 programmer and I am trying to create a windows desktop app that communicates with a Linux server over TCP or UDP sockets.  I just downloaded .Net Community 2019 and I can't find anything on sockets for VB.net, just C#.  

How can I get the functionality of VB6 winsock.ocx in VB.net?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Shaun KlineLead Software Engineer

Commented:
Syntax is the main difference between VB.Net and C#. The objects used in C# to perform socket calls will be the same in VB.Net.

Commented:
From a previous EE_PAQ; here is an extremely rudimentary client/server example.

Server Project -
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading

Module Module1
    Sub Main()
        Dim cts As CancellationTokenSource = New CancellationTokenSource()
        Dim listener As TcpListener = New TcpListener(IPAddress.Any, 28000)
        listener.Start()
        Console.WriteLine("Listener is waiting for client connections...")
        Dim task As Task = AwaitClientConnectionAsync(listener, cts.Token)

        While Not Console.ReadKey().Key.Equals(ConsoleKey.Q)
        End While

        cts.Cancel()

        While task.Status.Equals(TaskStatus.Running)
        End While
        Console.WriteLine()
        Console.WriteLine("Finished cancelling all tasks.  Press any key to exit.")
        Console.ReadLine()
    End Sub

    Async Function AwaitClientConnectionAsync(ByVal listener As TcpListener, ByVal token As CancellationToken) As Task
        While Not token.IsCancellationRequested
            Console.WriteLine("Task is waiting for client connection...")
            Console.WriteLine("Press 'Q' to quite...")
            Dim client As TcpClient = Await listener.AcceptTcpClientAsync()
            Console.WriteLine("Client requesting connection...")
            Dim task As Task = TrySendResponse(client, token)
            While task.Status.Equals(TaskStatus.Running)
            End While
        End While
    End Function

    Async Function TrySendResponse(ByVal client As TcpClient, ByVal token As CancellationToken) As Task
        Dim buffer As Byte() = New Byte(4096) {}
        Dim stream As NetworkStream = client.GetStream()
        token.Register(Sub() stream.Close())
        While Not token.IsCancellationRequested
            Try
                Dim read As Integer = Await stream.ReadAsync(buffer, 0, buffer.Length, token)
                If (read <> 0) Then
                    Console.WriteLine($"Received: {Encoding.UTF8.GetString(buffer, 0, read)}")
                Else
                    Exit While
                End If

                Await stream.WriteAsync(buffer, 0, read, token)
                Console.WriteLine("Response sent to client...")
                Console.WriteLine("Press 'Q' to quit...")
            Catch ex As Exception
                Console.WriteLine(ex.Message)
            End Try
        End While
    End Function
End Module

Open in new window

Client Project -
Imports System.IO
Imports System.Net
Imports System.Net.Sockets

Module Module1
    Sub Main()
        Dim [task] As Task = Task.Factory.StartNew(Async Sub()
                                                       Using client As TcpClient = New TcpClient()
                                                           Await client.ConnectAsync(IPAddress.Parse("127.0.0.1"), 28000)
                                                           Console.WriteLine("Connected to the server")
                                                           Using stream As NetworkStream = client.GetStream()
                                                               Using writer As StreamWriter = New StreamWriter(stream)
                                                                   Using reader As StreamReader = New StreamReader(stream)
                                                                       writer.AutoFlush = True
                                                                       For Each i In Enumerable.Range(0, 10)
                                                                           Console.WriteLine("Writing to the server")
                                                                           Await writer.WriteLineAsync(DateTime.Now.ToLongTimeString())
                                                                           Console.WriteLine("Reading response from the server")
                                                                           Dim response As String = Await reader.ReadLineAsync()
                                                                           If Not String.IsNullOrWhiteSpace(response) Then
                                                                               Console.WriteLine($"Response from server: {response}")
                                                                           End If
                                                                       Next
                                                                   End Using
                                                               End Using
                                                           End Using
                                                       End Using
                                                       Console.WriteLine("Client has closed connection to the server...")
                                                   End Sub)
        While task.Status.Equals(TaskStatus.Running)
        End While
        Console.WriteLine()
        Console.WriteLine("Client has finished executing...  Press any key to exit...")
        Console.ReadLine()
    End Sub
End Module

Open in new window

Running the server project first -Capture.PNGWith the server open, start the client -Capture.PNGServer window now shows -Capture.PNG-saige-

Author

Commented:
Thanks, it_saige.  Did you convert the C# in PAQ to VB?

I'll try this out.  Seems VB.net is not very VB6 like.
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Commented:
I did convert it since you were specifically seeking a VB.NET version.  And you are correct, VB.NET is a completely different animal compared to VB6.

-saige-

Author

Commented:
Thanks for your help!  I really miss my VB6 though.

Author

Commented:
-saige-
I get  BC30182 Type Expected on Client line 8.  Idea?

Author

Commented:
Also, if this is "ConnectAsync" doesn't that make it UDP not TCP?  Or am I confused about that?

Commented:
Make sure you have your Import statements, TcpClient is a member of System.Net.  As for ConnectAsync, it doesn't make the connection asynchronous, rather it makes an asynchronous request for a connection to the remote host.

You can read more about ConnectAsync here: https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.socket.connectasync?view=netframework-4.8

-saige-

Author

Commented:
I have exactly what you posted above. Does it work for you?

Author

Commented:
It seems all the documentation is about C# which does not help me with VB syntax errors, especially since I am new to VB.net and it is NOTHING like VB6.  Do you happen to know of a way to use sockets with VBA?

Commented:
The above does work for me (those screen shots are taken during the application running).  Check your .NET version for the projects.

To do so, right click on the project and select properties.  In the application tab, look for Target framework.  These projects were built under 4.5.2 so anything at that level or higher should be fine.

-saige-

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial