Sunday, November 17, 2013

.NET - Guide to Server Basics, Part I

It's moderately difficult to create a server application for the first time. This guide should help you establish a listener and an array of connections.

First, you're going to need to import System.Net.Sockets and System.IO. System.Threading is useful if you want a multithreaded listener. I recommend creating a class to hold connection objects.

Class ClientCon
 Public Client As TcpClient
 Public Stream As NetworkStream
 Public Reader As StreamReader
 Public Writer As StreamWriter
End Class
Dim Cons As New List(Of ClientCon)

The collection of connections is helpful to check all the clients in one sweep. Declare a listener as a TcpListener. I usually create a server class to manage all the servery stuff.

Class Server
 Public ShutDown As Boolean
 Public Listen As TcpListener
 Public Sub StartListening(Port As Integer)
  Listen = New TcpListener(IPAddress.Any, Port)
  Listen.Start()
  ThreadPool.QueueUserWorkItem( _
   New WaitCallback(AddressOf Listener))
 End Sub
 Public Sub Listener()
  Do
   If Listen.Pending() Then
    Dim c As New ClientCon
    c.Client = Listen.AcceptTcpClient()
    c.Stream = c.Client.GetStream()
    c.Reader = New StreamReader(c.Stream)
    c.Writer = New StreamWriter(c.Stream)
    c.Writer.AutoFlush = True
    Cons.Add(c)
   End If
  Loop
 End Sub
End Class

Creating a new instance of that class and telling it to start listening will create a new thread that listens for client connections, accepts them, and puts them in the connection list.

Next post, we'll get some communication and keep-alives going.

No comments:

Post a Comment