Click here to Skip to main content
Sign Up to vote bad
good
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:37
Edited 4 Oct '12 - 0:40

Comments
OriginalGriff - 4 Oct '12 - 6:44
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 - 4 Oct '12 - 6:48
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 - 4 Oct '12 - 6:58
You are so right! I missed that completely - post it as the solution so I can vote it!
Wes Aday - 4 Oct '12 - 7:00
Easy to miss. :-)
Umesh Sharma Kota - 4 Oct '12 - 7:05
Thank you very much Dear... I am really a new ... I proved it myself

1 solution

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
Your Filters
Interested
Ignored
     
0 Mohammed Hameed 268
1 OriginalGriff 236
2 Sergey Alexandrovich Kryukov 198
3 Mayur_Panchal 153
4 CPallini 100
0 Sergey Alexandrovich Kryukov 8,171
1 OriginalGriff 6,236
2 CPallini 3,482
3 Rohan Leuva 2,703
4 Maciej Los 2,234


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