Click here to Skip to main content
15,884,537 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
I am working on a structure that simplifies the process of creating a chat client. The code is designed to handle both listening for a connection and making a connection (its basically a server and a client). The code contains some Messagebox Show events which were used for testing. However, I keep running into a NullReferenceException. Can anyone help? Help would be very appreciated. :-)

VB
Imports System.Net
Imports System.Net.Sockets

Public Class Form1

    Public Structure StringChat
        Private client As TcpClient
#Region "Listening"
        Private islisten As Boolean
        Private lst As TcpListener
        Dim lt As Timer
        Function Startlistening(ByVal hostip As IPAddress, ByVal portnumber As Integer)
            If Cn = True Or islisten = True Then
                Return False
                Exit Function
            End If
            Try
                lst = New TcpListener(hostip, portnumber)
                lst.Start()
                islisten = True
                MsgBox(lst.Pending())
                lt.Start()
                role = "Listener"

                Return True
            Catch ex As Exception
                Return False
            End Try
        End Function

        Sub Stoplistenin()
            islisten = False
            lt.Enabled = False
            lst.Stop()
        End Sub
        Private Sub lisen(ByVal sender As Object, ByVal e As System.EventArgs)
            islisten = True
            If islisten = True Then

                'Null Reference Exception happens here
                If lst.Pending() = True Then
                    MessageBox.Show("Connecting")
                    client = lst.AcceptTcpClient
                    role = "Listener"
                    client.Client.BeginReceive(msg, 0, 1024, SocketFlags.None, AddressOf BeginRecieve, Nothing)
                End If
              
            End If
        End Sub
#End Region

#Region "Client"
        Sub Disconnect()
            If Cn = True Then
                Writemessage("*(DISCONNECT)*")
                client.Client.Disconnect(True)
                tm.Enabled = False
                RaiseEvent OnDisconnect(DateTime.Now)
            End If

        End Sub

        Function Connect(ByVal hostname As String, ByVal portnumber As Integer, ByVal password As String) As Boolean
            If Cn = True Or islisten = True Then
                Return False
                Exit Function
            End If
            If My.Computer.Network.Ping(hostname) = False Then
                Return False
                Exit Function
            End If
            Try
                client = New TcpClient(hostname, portnumber)

                client.Client.BeginReceive(msg, 0, 1024, SocketFlags.None, AddressOf BeginRecieve, Nothing)
                Return True
                If password = Nothing = False Then

                    Writemessage(password)
                Else
                    Writemessage("ACTIVATE()")
                End If
                role = "Connector"
                tm.Enabled = True
            Catch ex As Exception
                Return False
            End Try

        End Function

#End Region

        Dim tm As Timer

        Sub New(ByVal Listen As Boolean)
            Dim ms(1024) As Byte
            msg = ms
            tm = New Timer()
            AddHandler tm.Tick, AddressOf tm_Tick
            lt = New Timer()
            AddHandler lt.Tick, AddressOf lisen

        End Sub

        Private Sub tm_Tick(ByVal sender As Object, ByVal e As System.EventArgs)
            If msk = Nothing = False Then
                RecieveMessage(msk)
                msk = Nothing
            End If
        End Sub
#Region "MessageHandlers"
        Private msg() As Byte
        Private msk As String
        Private Sub BeginRecieve(ByVal i As IAsyncResult)
            msk = System.Text.Encoding.ASCII.GetString(msg)
            Dim ms(1024) As Byte
            msg = ms
            If Cn = True Then
                client.Client.BeginReceive(msg, 0, 1024, SocketFlags.None, AddressOf BeginRecieve, Nothing)
            End If
        End Sub
        Private Sub RecieveMessage(ByVal ms As String)

            If ms = "*(DISCONNECT)*" Then

                tm.Enabled = False
                If Cn = True Then
                    RaiseEvent OnDisconnect(DateTime.Now)
                End If
                Cn = False
                Exit Sub
            End If
            If ms = "*(ACCEPTED)*" Then
                Cn = True
                tm.Enabled = True
                Exit Sub
            End If
            If role = "Listener" Then
                If ra = True Then
                    If Passcde = ms Then
                        Writemessage("*ACCEPTED)*")
                        Cn = True
                        tm.Enabled = True
                    Else
                        Writemessage("*(DISCONNECT)*")
                        client.Client.Disconnect(True)
                        tm.Enabled = False
                        RaiseEvent OnDisconnect(DateTime.Now)
                    End If
                Else
                    Writemessage("*ACCEPTED)*")
                    Cn = True
                    tm.Enabled = True
                End If
                Exit Sub
            End If
            RaiseEvent RecievedMessage(ms)
        End Sub

        Function Writemessage(ByVal Message As String) As Boolean
            If Cn = True Then
                Try
                    Dim sw As New IO.StreamWriter(client.GetStream())
                    sw.Write(Message)
                    sw.Flush()
                    sw.Dispose()

                    Return True
                Catch ex As Exception

                    Return False
                End Try
            Else

                Return False
            End If

        End Function
#End Region

#Region "Properties"
        Event RecievedMessage(ByVal Message As String)
        Event OnDisconnect(ByVal timestamp As DateTime)
        Private ra As Boolean
        Private Passcde As String
        Private Cn As Boolean
        Private role As String
        Property RequireAuthentication() As Boolean
            Get
                Return ra
            End Get
            Set(ByVal value As Boolean)
                ra = value
            End Set
        End Property
        Property Passcode() As String
            Get
                Return Passcde
            End Get
            Set(ByVal value As String)
                Passcde = value
            End Set
        End Property
        ReadOnly Property Islistening() As Boolean
            Get
                Return islisten
            End Get
        End Property
        Property Connected() As Boolean
            Get
                Return Cn
            End Get
            Set(ByVal value As Boolean)
                Cn = value
            End Set
        End Property
#End Region

    End Structure


    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim st1 As New StringChat(False)
        Dim st2 As New StringChat(False)
        AddHandler st2.RecievedMessage, AddressOf rmessage
        AddHandler st1.OnDisconnect, AddressOf disconnected
        st2.RequireAuthentication = True
        st2.Passcode = "1234"
        st2.Startlistening(Dns.GetHostEntry(Dns.GetHostName()).AddressList(1), 18000)
      
        If st1.Connect("192.168.1.65", 18000, Nothing) = True Then
            MessageBox.Show("Connected")
        Else
            MessageBox.Show("Failed To Connect")
        End If

    End Sub
    Private Sub rmessage(ByVal msg As String)
        MessageBox.Show("INBOX:" & msg)
    End Sub
    Private Sub disconnected(ByVal ts As DateTime)
        MessageBox.Show("Lost Connection", "Warning")
    End Sub
End Class
Posted
Comments
Sergey Alexandrovich Kryukov 11-May-12 21:47pm    
This exception is one of the easiest to find out. Why wouldn't you run it under debugger and tell us exact line where it happens?
--SA

1 solution

NullReferenceException
This error happens when you try to use a property of an object that is null. More details: here[^]

A simple use of Visual studio DEBUGGER can tell you the object because of which it is happening. Just look at the stack trace and put a debugger on that line. Check the objects of that line and see if any one is null and you are trying to use that objects property. Handle the same.
 
Share this answer
 

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



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