Click here to Skip to main content
15,881,938 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I have some server code to accept a TCP connection from another computer and to display a message in a listbox on the server.

"Receiver" is the name of a backgroundworker.

I've only displayed relevant code here:

VB
Private Sub Receiver_DoWork(ParametersWereHere) Handles Receiver.DoWork
       Try
           Dim TCPListener As New TcpListener(IncomingPort)
           TCPListener.Start()
           While True
               client = New ClientConnection(TCPListener.AcceptTcpClient, AddressOf ListBoxUpdater)
           End While
       Catch ex As Exception
           MsgBox("3. " & ex.Message)
       End Try
   End Sub
   Private Sub ListBoxUpdater(ByVal WhatToWrite As String)
       If Me.InvokeRequired Then
     ***** Me.Invoke(client.UpdateListBox, WhatToWrite) *****
       Else
           Me.ListBox2.Items.Add(WhatToWrite)
       End If
   End Sub


And in the class ClientConnection:

VB
Public Delegate Sub UpdateListInvoker(ByVal WhatToWrite As String)
    Public UpdateListBox As UpdateListInvoker
    Public Sub New(ByVal Client As TcpClient, ByRef _callback As UpdateListInvoker)
        UpdateListBox = _callback
        TCPClient = Client
        ClientIP = Client.Client.RemoteEndPoint.ToString
        AllClients.Add(ClientIP, Me)
        UpdateListBox("Connected: " & ClientIP)
        ReDim data(TCPClient.ReceiveBufferSize)
        TCPClient.GetStream.BeginRead(data, 0, CInt(TCPClient.ReceiveBufferSize), AddressOf ReceiveMessage, Nothing)
    End Sub


The problem I'm facing is that on the starred line in the first code block, I get the error

object reference not set to an instance of an object


when I comment out the "try... catch... end try" statement in Receiver_DoWork().

The Watch window showed that "client" was empty, but it should have a ClientConnection assigned to it.

Can anyone see what's wrong here?

-Rixterz
Posted
Updated 8-Nov-14 10:59am
v5
Comments
Sergey Alexandrovich Kryukov 8-Nov-14 21:36pm    
There is no need in InvokeRequired. It will always return true, because you always call it in the non-UI thread (so, invoke is always required).
Where exactly the exception is thrown?
—SA
[no name] 9-Nov-14 6:35am    
On the starred line
Sergey Alexandrovich Kryukov 9-Nov-14 13:08pm    
I see, thank you. Use the debugger and inspect what object which are not supposed to be null appears null. Such problem is one of the easiest to debug and fix.
—SA
[no name] 9-Nov-14 14:22pm    
I saw that client was empty.
Sergey Alexandrovich Kryukov 9-Nov-14 14:38pm    
You are facing null problem, not empty...
—SA

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