This example demonstrates how to use Chilkat.Socket to create a Windows Service in VB.NET that listens at a port and handles multiple simultaneous client connections. Each client is handled in a separate thread. The Windows Service may be stopped at any time.
Note:The Chilkat .NET assembly DLL must be installed in the Global Assembly Cache (GAC) for Windows Services. (This is not a requirement for non-Service applications or ASP.NET applications — it is only a requirement for Services.)
Chilkat.Service VB.NET Examples
Chilkat.Service C# Examples
The VB.NET Socket Server Code
Creating a Windows Service in VB.NET is easy. Choose "Windows Service" from the list of available templates when creating the project. You’ll need to add implementations for "OnStart" and "OnStop".
The OnStart code creates the socket for listening at a specified port and begins accepting connections. A thread is created to listen for incoming connections and the OnStart method returns control to the caller.
Protected Overrides Sub OnStart(ByVal args() As String)
' Create a socket to be used for listening for connections.
m_listenSock = New Chilkat.Socket
' Unlock the component. Any string automatically begins a 30-day trial.
Dim success As Boolean
success = m_listenSock.UnlockComponent("Anything for 30-day trial")
If (success <> True) Then
m_listenSock.SaveLastError(m_logDir & "lastError.xml")
Exit Sub
End If
' Listen on a port for incoming connections.
Dim port As Integer
Dim backLog As Integer
port = 8220
backLog = 5
success = m_listenSock.BindAndListen(port, backLog)
If (success <> True) Then
m_listenSock.SaveLastError(m_logDir & "lastError.xml")
Exit Sub
End If
' Begin accepting connections...
Dim t As Thread
t = New Thread(AddressOf Me.AcceptConnections)
m_numActiveThreads = m_numActiveThreads + 1
t.Start()
End Sub
Here’s our class data members:
Public Class Service1
Dim m_logDir As String = "c:\MyServices\TestServer1\"
Dim m_listenSock As Chilkat.Socket
' This gets set to True when the service is shutdown. Threads
' will react to this and exit/abort appropriately.
Dim m_stopRequested As Boolean = False
' The number of (extra) threads still running.
Dim m_numActiveThreads As Integer = 0
...
The AcceptConnections method runs in a thread who’s sole purpose is to accept incoming client connections:
' This subroutine runs in a background thread and accepts incoming connections.
' It starts a new thread for each connection accepted.
Private Sub AcceptConnections()
Dim sock As Chilkat.Socket
' Accept connections until the service needs to be stopped.
Do While Not m_stopRequested
' Wait for an incoming connection. Wait a max of 1 second.
sock = m_listenSock.AcceptNextConnection(1000)
If (Not (sock Is Nothing)) Then
Dim t As Thread
t = New Thread(AddressOf Me.HandleClient)
m_numActiveThreads = m_numActiveThreads + 1
t.Start(sock)
End If
Loop
m_numActiveThreads = m_numActiveThreads - 1
End Sub
A thread is started for each connected client. The connected socket is passed to the HandleClient method. This server is very simple: it reads a string from the client, then responds by sending a message back to the client, and disconnects.
Private Sub HandleClient(ByVal obj As Object)
Dim sock As Chilkat.Socket
sock = obj
' Set read and write timeouts to 5 seconds.
sock.MaxReadIdleMs = 5000
sock.MaxSendIdleMs = 5000
' This sample server will read a string until it receives a CRLF.
' It then sends a "Hello Client!" + CRLF back to the client.
Dim strFromClient = sock.ReceiveToCRLF()
' A null reference is returned if it failed.
' Also, if a stop is requested, just exit.
If m_stopRequested Or (strFromClient Is Nothing) Then
m_numActiveThreads = m_numActiveThreads - 1
Exit Sub
End If
' Send our response
Dim success As Boolean
success = sock.SendString("Hello Client!" & vbCrLf)
' Don't bother checking the return status because we're done with
' this client anyway...
' The maxWaitMs only has an effect when shutting down SSL connections...
Dim maxWaitMs As Integer
maxWaitMs = 100
sock.Close(maxWaitMs)
m_numActiveThreads = m_numActiveThreads - 1
End Sub
The OnStop method works by setting a flag (m_stopRequested) that each of the other threads will notice. Each thread exits after noticing that a stop has been requested. Here’s the OnStop code:
Protected Overrides Sub OnStop()
m_stopRequested = True
' Wait for threads to exit, but wait a max of 10 seconds..
Dim counter As Integer = 0
Do While (m_numActiveThreads > 0) And (counter < 100)
counter = counter + 1
System.Threading.Thread.Sleep(100)
Loop
End Sub
The client-side code is simple:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim socket As New Chilkat.Socket
Dim success As Boolean
success = socket.UnlockComponent("Anything for 30-day trial")
If (success <> True) Then
MessageBox.Show("Failed to unlock component")
Exit Sub
End If
' Connect to TestServer1 at port 8220
Dim ssl As Boolean
Dim maxWaitMs As Integer
ssl = False
maxWaitMs = 2000
success = socket.Connect("localhost", 8220, ssl, maxWaitMs)
If (success <> True) Then
MessageBox.Show(socket.LastErrorText)
Exit Sub
End If
' Send a string to the server ending in CRLF
success = socket.SendString("This is a test" & vbCrLf)
If (success <> True) Then
MessageBox.Show(socket.LastErrorText)
Exit Sub
End If
' Now get the response.
Dim svrResponse As String
svrResponse = socket.ReceiveToCRLF()
If (svrResponse Is Nothing) Then
MessageBox.Show(socket.LastErrorText)
Exit Sub
End If
MessageBox.Show(svrResponse)
End Sub