DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Server Side Connecting / Comminicating Class

10.04.2006
| 492 views |
  • submit to reddit
        // Server code

Imports System.Net.Sockets
Imports System.Text
Imports System.Windows.Forms
Public Class ServerObj
    Private tcpListener As TcpListener
    Private isRunning As Boolean = False
    Private clientList As New ArrayList()
    Private listenPulse As Timer
    Public MaxClients As Integer = 5
    Private portNumber As Integer = -1
    Public ReadOnly Property Running()
        Get
            Return Me.isRunning
        End Get
    End Property
    Public Sub New(ByVal port As Integer, ByVal maxConnections As Integer)
        Try
            Me.MaxClients = maxConnections
            Me.portNumber = port
            tcpListener = New TcpListener(System.Net.IPAddress.Any, port)
            Me.listenPulse = New Timer()
            Me.listenPulse.Interval = 250
            AddHandler listenPulse.Tick, AddressOf listenPulseTick
        Catch ex As Exception
            Throw New Exception("Unable to start server! Error: " & ex.Message)
        End Try
    End Sub
    Public Sub StartServer()
        Me.isRunning = True
        tcpListener.Start()
        Me.listenPulse.Start()
    End Sub
    Public Sub StopServer()
        Me.listenPulse.Stop()
        Me.isRunning = False
        tcpListener.Stop()
        Me.closeConnections()
    End Sub
    Private Sub closeConnections()
        Me.listenPulse.Stop()
        For clientId As Integer = 0 To Me.clientList.Count - 1
            Dim client As TcpClient = Me.clientList(clientId)
            client.Close()
        Next
        Me.listenPulse.Start()
    End Sub
    Private Sub checkForPendingClients()
        Me.listenPulse.Stop()
        While Me.tcpListener.Pending And Me.clientList.Count <= Me.MaxClients
            Me.clientList.Add(Me.tcpListener.AcceptTcpClient())
            RaiseEvent ClientConnected(Me.clientList.Count - 1)
        End While
        Me.listenPulse.Start()
    End Sub
    Public Function ClientCount() As Integer
        Return Me.clientList.Count
    End Function
    Public Sub ClientClosed(ByVal clientId As Integer)
        Me.listenPulse.Stop()
        DirectCast(Me.clientList(clientId), TcpClient).Close()
        Me.listenPulse.Start()
    End Sub
    Public Event ClientMessage(ByVal clientId As Integer, ByVal clientMsg As String)
    Public Event ClientConnected(ByVal clientId As Integer)
    Public Sub SendToAllClients(ByVal msg As String)
        For clientId As Integer = 0 To Me.clientList.Count - 1
            Me.SentToClient(clientId, msg)
        Next
    End Sub
    Public Sub SentToClient(ByVal clientId As Integer, ByVal msg As String)
        Me.listenPulse.Stop()
        Dim client As TcpClient = Me.clientList(clientId)
        If client.Client.Connected Then
            msg = msg & "|"
            Dim networkStream As NetworkStream = client.GetStream()
            Dim responseString As String = msg
            Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(responseString)
            networkStream.Write(sendBytes, 0, sendBytes.Length)
            Me.listenPulse.Start()
        End If
    End Sub
    Private Sub listenPulseTick(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Try
            If Me.isRunning Then
                Me.listenPulse.Stop()
                Me.checkForPendingClients()
                For clientId As Integer = 0 To Me.clientList.Count - 1
                    Dim client As TcpClient = Me.clientList(clientId)
                    If client.Connected Then
                        Dim networkStream As NetworkStream = client.GetStream()
                        If networkStream.DataAvailable Then
                            Dim bytes(client.ReceiveBufferSize) As Byte
                            networkStream.Read(bytes, 0, CInt(client.ReceiveBufferSize))
                            Dim clientdata As String = ""
                            For i As Integer = 0 To bytes.Length - 1
                                If bytes(i) <> 0 Then
                                    clientdata &= Encoding.ASCII.GetString(bytes, i, 1)
                                End If
                            Next
                            If clientdata <> "" Then
                                Dim queued As String() = clientdata.Split("|")
                                For Each str As String In queued
                                    If str <> "" Then
                                        RaiseEvent ClientMessage(clientId, str)
                                    End If
                                Next
                            End If
                        End If
                    End If
                Next
                Me.listenPulse.Start()
            End If
        Catch ex As Exception
            Me.StopServer()
            Throw New Exception("Server Terminal Error: " & ex.Message)
        End Try
    End Sub
End Class