Winsock for VB.Net Community 2019

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?
LVL 1
jrigginAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Shaun KlineLead Software EngineerCommented:
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.
it_saigeDeveloperCommented:
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-
jrigginAuthor 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.
Your Guide to Achieving IT Business Success

The IT Service Excellence Tool Kit has best practices to keep your clients happy and business booming. Inside, you’ll find everything you need to increase client satisfaction and retention, become more competitive, and increase your overall success.

it_saigeDeveloperCommented:
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-

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
jrigginAuthor Commented:
Thanks for your help!  I really miss my VB6 though.
jrigginAuthor Commented:
-saige-
I get  BC30182 Type Expected on Client line 8.  Idea?
jrigginAuthor Commented:
Also, if this is "ConnectAsync" doesn't that make it UDP not TCP?  Or am I confused about that?
it_saigeDeveloperCommented:
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-
jrigginAuthor Commented:
I have exactly what you posted above. Does it work for you?
jrigginAuthor 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?
it_saigeDeveloperCommented:
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-
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.