Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: VB.NET
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." ???
==============================================================================
 
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]
Posted 4-Oct-12 0:37am
Edited 4-Oct-12 0:40am
v2
Comments
OriginalGriff at 4-Oct-12 6:44am
   
Are you sure?
Put a breakpoint on the line
Dim sckt As Socket = tcpLsn.AcceptSocket()
and see what the value of tcpLsn is - that is the only reference to it in the method, and it appears to be set in the constructor. So unless you are overwriting it elsewhere, it shouldn't be that.
Wes Aday at 4-Oct-12 6:48am
   
You have declared it twice. Once at the form level and once local to the constructor. Then you are using the form level variable in that method and it's still null.
OriginalGriff at 4-Oct-12 6:58am
   
You are so right!
I missed that completely - post it as the solution so I can vote it!
Wes Aday at 4-Oct-12 7:00am
   
Easy to miss. :-)
Umesh Sharma Kota at 4-Oct-12 7:05am
   
Thank you very much Dear...
I am really a new ... I proved it myself

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

You have declared it twice. Once at the form level and once local to the constructor. Then you are using the form level variable in that method and it's still null.
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 330
1 Sergey Alexandrovich Kryukov 295
2 ClimerChinna 207
3 Magic Wonder 205
4 Gihan Liyanage 192
0 Sergey Alexandrovich Kryukov 8,188
1 OriginalGriff 6,991
2 CPallini 2,598
3 Richard MacCutchan 1,925
4 Abhinav S 1,736


Advertise | Privacy | Mobile
Web02 | 2.8.140826.1 | Last Updated 4 Oct 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100