Monday, November 18, 2013

.NET - Guide to Server Basics, Part II

Now that you have a listener to catch new connections, it's time to actually communicate with them. I recommend another thread for reading in data. We'll use a queue of messages, but we'll need a new class to keep track of messages.

Public Class QueuedMessage
 Public Received As DateTime
 Public Data As String
 Public Sender As ClientCon
 Public Sub New(R As DateTime, D As String, S as ClientCon)
  Received = R
  Data = D
  Sender = ClientCon
 End Sub
End Class

Now we can make that queue and add data-reading and message-processing loops.

Public ProcessQueue As New List(Of QueuedMessage)
Public Sub ReadData()
 Do
  For Each c In Cons
   Try
    If Not c.Connected Then Exit Try
    Dim s As String = c.Reader.ReadLine()
    Dim msg As New QueuedMessage(Now, s, c)
    If Trim(s) <> "" Then ProcessQueue.Add(msg)
   Catch ex As Exception
   End Try
  Next
 Loop
End Sub
Public Sub ProcessLines()
 Do
  If ProcessQueue.Count > 0 Then
   Dim d As QueuedMessage = ProcessQueue(0)
   'Your handling code here using d
   ProcessQueue.RemoveAt(0)
  End If
 Loop
End Sub

Insert calls to start threads for those loops to the server's initialization sub. For convenience, I recommend having a writing sub in the connection class. Also, soon we'll need a time field to keep track of keep-alives.

Public LastKA As DateTime
Public Sub Send(Data As String)
 Writer.WriteLine(Data)
End Sub

Set the timer and give the client a little head start in the client acceptance code:

c.LastKA = Now.AddSeconds(5)

With that ready, insert a line into the data-reading loop that resets that field when data is received.

c.LastKA = Now

Prepare to enforce the timeout.

Public Sub Discon(Con As ClientCon)
 Con.Client.Close()
 Cons.Remove(Con)
End Sub

Finally, add a check loop sub.

Public Sub CheckKA()
 Do
  For Each c In Cons
   If c.LastKA.AddSeconds(10) < Now Then Discon(c)
  Next
 Loop
End Sub

Just make sure to have the client send updates or useless KA messages once every few seconds. I'm not sure what I'll cover next time.

No comments:

Post a Comment