Basic TCP/IP Server
Basic TCP/IP Server
Basic TCP/IP Server
Basic TCP/IP Server
Basic TCP/IP Server
Basic TCP/IP Server Basic TCP/IP Server Basic TCP/IP Server Basic TCP/IP Server Basic TCP/IP Server Basic TCP/IP Server Basic TCP/IP Server Basic TCP/IP Server
Basic TCP/IP Server Basic TCP/IP Server
Basic TCP/IP Server
Go Back  Xtreme Visual Basic Talk > > > Basic TCP/IP Server


Reply
 
Thread Tools Display Modes
  #1  
Old 03-03-2011, 02:49 AM
philman philman is offline
Freshman
 
Join Date: Mar 2011
Posts: 32
Default Basic TCP/IP Server


Up until now I have been using VB6 with a winsock object. I am a newbie on VB.net and I cannot wrap my mind around sockets. I have searched this forum and googled for articles, but I am still struggling. I would appreciate some tips on getting me started with sockets.

In VB6 I added one winsock component to the form and in the ConnectionRequest event I would create a new winsock object for each client:
Code:
Load Winsock1(newSocket)
Winsock1(newSocket).Accept requestID
In the DataArrival events I would receive the data from the various sockets and reply to the clients.
When the client closed the socket, the Close event would run and I then closed the relevant Winsock object:
Code:
Winsock1(Index).Close
Unload Winsock1(Index)
How would I do the equivalent in VB.net? I am a newbie in VB.net and although I did not program at an advanced level in VB6, I managed to get the server to work.

Your comments would be much appreciated.

Last edited by philman; 03-03-2011 at 06:18 AM.
Reply With Quote
  #2  
Old 03-03-2011, 10:03 AM
AtmaWeapon's Avatar
AtmaWeaponBasic TCP/IP Server AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,500
Default

I think it's likely you should switch gears, I'll explain with a car analogy.

Some people prefer to drive a car with a manual transmission. Since a manual lets you control the gear used to transfer power from the engine to the wheels, a skilled driver can get better performance and better gas mileage. Most people prefer to use cars with automatic transmissions. These drivers sacrifice a small amount of power and efficiency in favor of an easier driving experience. I've seen a great speech that talked about this but it boils down to a simple point: most people aren't driving a car because they want to drive; they drive a car because they're trying to go somewhere. If they could teleport, they wouldn't use the car at all. So asking these people to use a manual transmission is just making the part they don't really want to do harder.

The Socket class is like a manual transmission. You can control every byte down to the protocol level, but if you're just trying to send some data from A to B you have to go through a lot of ritual. Most people start with TcpClient and TcpListener, the automatic transmission of the System.Net namespace. These classes implement the TCP protocol for you and hide most of the nastiness behind a friendly API.

To write a server, you create a TcpListener and call its Start() method. After that, you check Pending() to see if any connections are incoming and if there are connections you call AcceptTcpClient() to accept the connection. It returns a TcpClient and you can use the stream it returns from GetStream() to receive data.

To write a client, you create a TcpClient and call Connect(). Once a connection is established, you use GetStream() to get a stream you can use to send data.

Read the documentation for these classes and do some searching of the forums and the rest of the internet for a bit; there's enough tutorials it's hard to justify adding another.
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.
Reply With Quote
  #3  
Old 03-04-2011, 12:54 AM
philman philman is offline
Freshman
 
Join Date: Mar 2011
Posts: 32
Default

Thanks for the informative reply Atma. I have looked at a few examples on the web, and they are all similar in that they create a TcpListener object and call its Start method and then Stop method within the class, which is not what I want to do.
After reading your response and looking at examples, I would like to do the following:

In the Form_Load event create a TcpListener object and call its Start() method. (never call the Stop() method)
Then:
In an infinite loop check Pending(). If there are connections, then create an AcceptTcpClient() object for that socket, and create a GetStream() object to receive the data and reply. Then close the AcceptTcpClient() object and continue to check Pending().

Later on, when I understand threading, I will create a new thread for each socket, but initially I will have to queue the clients. In my application the clients are going to send a few hundred bytes of data and then they will close the socket immediately.

In the object browser I see that TcpListener does not have any events, so I assume there is no such thing as a connection request event - instead of checking Pending(), or a timeout event.

Am I on the right track ?
Reply With Quote
  #4  
Old 03-04-2011, 10:55 AM
AtmaWeapon's Avatar
AtmaWeaponBasic TCP/IP Server AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,500
Default

Your plan is sound, but I think it's silly to say you will never call Stop(). Will your application run forever? Certainly you'll want to close it one day, especially during debugging.

There are indeed no events that are raised when a connection attempt is made; you have to poll. I'm not really sure why they didn't abstract this away, but that's the API we have to live with.
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.
Reply With Quote
  #5  
Old 03-05-2011, 11:53 PM
philman philman is offline
Freshman
 
Join Date: Mar 2011
Posts: 32
Default

Thanks Atma. The reason why I don't want to call Stop() is because it has to listen on a particular port forever. I assumed that for debugging I would stop the application and install the new exe file (with bugfix), and debugging would be done on VB 2010 Express, or by the time the bug shows up I will use VB 2020 Express. Just kidding, I expect plenty of bugs
Reply With Quote
  #6  
Old 03-13-2011, 04:14 PM
PrOpHeT's Avatar
PrOpHeTBasic TCP/IP Server PrOpHeT is offline
Hopelessly confused...

* Expert *
 
Join Date: Mar 2001
Location: Tyler, Tx.
Posts: 3,055
Default

Perhaps I misunderstood the question, but if you use the Async method .BeginAcceptTcpClient it does the polling for you and performs the callback on each new client.

In this case ServerCore is a TcpListener instance.

Code:
 With ServerCore
                        .Start()
                        .BeginAcceptTcpClient(New AsyncCallback(AddressOf OnClientConnect), ServerCore)
                    End With
And continues to listen.

Certianly there is a sample of an AsyncTCP listener over there?
__________________
When you earnestly believe you can compensate for a lack of skill by doubling your efforts, there's no end to what you can't do ;)

For the love of Gold...
Reply With Quote
  #7  
Old 03-14-2011, 10:10 AM
AtmaWeapon's Avatar
AtmaWeaponBasic TCP/IP Server AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,500
Default

Properly implementing that would require a little more background information. In particular, it really matters if it's a GUI application or console application. Now I feel like implementation details are required.

Either way polling occurs, but in the GUI application it's abstracted away from you.

In a console application without using the async method, I'd envision a loop like this:
Code:
Sub Main()
    _listener = CreateTcpListener()
    _listener.Start()
    While True
        If _listener.Pending() Then
            Dim client = AcceptTcpClient()
            ' Do something with the client
        Else
            Console.WriteLine("Waiting...")
            Thread.Sleep(5000)
        End If

        If SomeExitCondition() Then
            Exit While
        End If
    End While

    _listener.Stop()
End Sub
Try the equivalent in a GUI app and of course the UI freezes while waiting for connections. You can handle it by moving that synchronous code to a worker thread or by using the APM pattern with code like this:
Code:
Private _operationTokens As New Dictionary(Of Object, IAsyncResult)()

Private Sub SomeEventHandler(...) Handles ???
    Dim id As New Object()
    Dim token As IAsyncResult = _listener.BeginAcceptTcpClient(AddressOf ClientCallback, Nothing)
    _operationTokens.Add(id, token)
End Sub

Private Sub ClientCallback(ByVal id As Object)
    Dim result As TcpClient = _listener.EndAcceptTcpClient(_operationTokens(id))
    ' .... do some stuff
End Sub
Note this is ignoring the extra work from the callback to avoid cross-thread calls to work with controls (though there's not a GUI-bound technique for avoiding that.) You can certainly do it in a console application, but then you'd have to have the main thread loop and poll for the exit condition, so it'd be a bit like using a crane to crush a fly.

Generally I'd want to write a simple server program as a console application because the complexity of multithreading is just another place to get it wrong. If I knew I wanted to use threads, say one per client connection, I might suck it up and do a UI app for the sake of having a better UI.

Either way, that's 90% of an example
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.
Reply With Quote
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Forum Jump

Advertisement:





Free Publications
The ASP.NET 2.0 Anthology
101 Essential Tips, Tricks & Hacks - Free 156 Page Preview. Learn the most practical features and best approaches for ASP.NET.
subscribe
Programmers Heaven C# School Book -Free 338 Page eBook
The Programmers Heaven C# School book covers the .NET framework and the C# language.
subscribe
Build Your Own ASP.NET 3.5 Web Site Using C# & VB, 3rd Edition - Free 219 Page Preview!
This comprehensive step-by-step guide will help get your database-driven ASP.NET web site up and running in no time..
subscribe
Basic TCP/IP Server
Basic TCP/IP Server
Basic TCP/IP Server Basic TCP/IP Server
Basic TCP/IP Server
Basic TCP/IP Server
Basic TCP/IP Server Basic TCP/IP Server Basic TCP/IP Server Basic TCP/IP Server Basic TCP/IP Server Basic TCP/IP Server Basic TCP/IP Server
Basic TCP/IP Server
Basic TCP/IP Server
 
Basic TCP/IP Server
Basic TCP/IP Server
 
-->