Click here to Skip to main content
15,897,718 members

NullReferenceException in vb.net

Umesh Sharma Kota asked:

Open original thread
Hi friends
I am new to VB.NET...
Can you please solve the run time error of "NullReferenceException" in following code which was generated due to object "tcpLsn" in "WatingForClient".
Why "Object reference not set to an instance of an object." ???
==============================================================================

VB
Imports System.Net.Sockets
Imports System.Text
Imports System.Net
Imports System.Threading

Public Class Form1
    Dim tcpLsn As TcpListener
    Dim sckt As Socket
    Dim SocketHolder As New Hashtable()
    Dim ThreadHolder As New Hashtable()
    Dim UserHolder As New Hashtable()
    Dim fThd As Threading.Thread
    Dim ConnectID As Integer = 0
    Dim KeepUser As Boolean
    Dim MaxConnected As Integer = 400

    Public Sub New()
        InitializeComponent()
        Dim ipAddress As IPAddress = Dns.GetHostEntry("localhost").AddressList(0)
        Dim tcpLsn = New TcpListener(ipAddress, 8002)
        tcpLsn.Start()
        MessageBox.Show("Server Started")
        Dim tcpThd = New Thread(New ThreadStart(AddressOf WaitingForClient))
        ThreadHolder.Add(ConnectID, tcpThd)
        tcpThd.Start()
    End Sub

    Public Sub WaitingForClient()
        While (True)
            'Accept will block until someone connects
            Dim sckt As Socket = tcpLsn.AcceptSocket()
            If ConnectID < 10000 Then
                ConnectID += 1
            Else
                ConnectID = 1
            End If
            If (SocketHolder.Count < MaxConnected) Then
                While (SocketHolder.Contains(ConnectID))
                    Interlocked.Increment(ConnectID)
                End While
                Dim td = New Thread(New ThreadStart(AddressOf ReadSocket))
                'it is used to keep connected Sockets
                SocketHolder.Add(ConnectID, sckt)
                'it is used to keep the active thread
                ThreadHolder.Add(ConnectID, td)
                td.Start()
            End If
        End While
    End Sub
    Public Sub ReadSocket()
        'realId will be not changed for each thread, 
        'but connectId is changed. it can't be used to delete object from Hashtable
        Dim realId As Integer = ConnectID
        Dim Ind As Integer = -1
        Dim s As Socket = SocketHolder(realId)
        While (True)
            If (s.Connected) Then
                Dim receive(37) As Byte
                Try
                    'Receive will block until data coming
                    'ret is 0 or Exception happen when Socket connection is broken
                    Dim ret = s.Receive(receive, receive.Length, 0)
                    If (ret > 0) Then
                        Dim tmp As String = Nothing
                        tmp = System.Text.Encoding.ASCII.GetString(receive)
                        If (tmp.Length > 0) Then
                            Dim strArry() = tmp.Split(":")
                            Dim code As Integer = CheckUserInfo(strArry(0))
                            If (code = 2) Then
                                UserHolder.Add(realId, strArry(0))
                            ElseIf (code = 1) Then
                                Dim connFail As String = String.Format(":The user {0} is connected already", strArry(0))
                                Dim byteData() As Byte = System.Text.Encoding.ASCII.GetBytes(connFail.ToCharArray())
                                s.Send(byteData, byteData.Length, 0)
                                s.Close()
                            ElseIf (code = 0) Then
                                Dim connFail As String = String.Format(":The user {0} is invalidate", strArry(0))
                                Dim byteData() As Byte = System.Text.Encoding.ASCII.GetBytes(connFail.ToCharArray())
                                s.Send(byteData, byteData.Length, 0)
                                s.Close()
                            End If
                        End If
                    Else
                        KeepUser = False
                    End If
                Catch
                    If Not (s.Connected) Then
                        KeepUser = False
                    End If
                End Try
            End If
        End While
        CloseTheThread(realId)
    End Sub
    Private Function CheckUserInfo(ByVal userID As String)
        'check the userId and password first
        '....
        If (True) Then     'suppose it ok
            If (UserHolder.ContainsValue(userID)) Then
                KeepUser = True
                Return 1   'user is login already
            End If
        End If
        Return 2           'user is vailidate
    End Function

    Private Sub CloseTheThread(ByVal realId)
        If Not (KeepUser) Then
            UserHolder.Remove(realId)
        End If
        Dim thd = ThreadHolder(realId)
        SocketHolder.Remove(realId)
        ThreadHolder.Remove(realId)
        If (thd.IsAlive) Then
            thd.Abort()
        End If
    End Sub

    Private Sub SendDataToAllClient(ByVal str)
        For Each sKey In SocketHolder.Keys
            Dim s As Socket = SocketHolder(sKey)
            If (s.Connected) Then
                Dim byteData() As Byte = System.Text.Encoding.ASCII.GetBytes(str.ToCharArray())
                Try
                    s.Send(byteData, byteData.Length, 0)
                Catch
                    'remove the bad client
                    CloseTheThread(sKey)
                End Try
            End If
        Next
    End Sub
End Class


[edit]Code block added - OriginalGriff[/edit]
Tags: Visual Basic

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900