TCP Socket (re-connecting) issue

qsrtech

Active Member
Licensed User
Longtime User
Hi I'm using TCP "Socket" to connect to a POS printer. Everything connects fine and communicates fine. The problem arises after I call ASocket.Close. When I try to reuse my Socket by calling ASocket.Connect again later, the Successful is always false in the connected event.

I'm not sure if this is related, but I do have similar issues when using B4A Bridge. Essentially if my connection get's lost, when I try to re-connect, it fails. I either have to re-start bridge on my device, which doesn't always help, or re-start b4a. Any ideas or suggestions regarding the socket issue?
 

qsrtech

Active Member
Licensed User
Longtime User
Last Exception

Hi Erel, this is what i get when adding log(lastexception) to the Socket_Connected event:

First Time connecting:
(Exception) Not initialized

Everytime after first "Close"
(NullPointerException) java.lang.NullPointerException

Note: I also checked lastexception before and after Socket.Close and both are Not Initalized
 

qsrtech

Active Member
Licensed User
Longtime User
lastexception

that is the lastexception in the connect event when false
 

qsrtech

Active Member
Licensed User
Longtime User
code

Working now. Thanks! See comment in cmdConnect_Click

B4X:
Sub Activity_Create(FirstTime As Boolean)
   'Do not forget to load the layout file created with the visual designer. For example:
   Activity.LoadLayout("tcpPrinterTest")
   If ASocket.IsInitialized=False Then
      ASocket.Initialize("ASocket")
   End If
   If aUDP.IsInitialized=False Then
      aUDP.Initialize("UDP",0,1024)
   End If
End Sub

Sub cmdConnect_Click
   'just added this If then and everything works correctly now
    'must have missed the details that initializing was required again after a close
    If ASocket.IsInitialized=False Then
      ASocket.Initialize("ASocket")
   End If
   ASocket.Connect(txtServer.Text,txtPort.Text,5000)
End Sub

Sub ASocket_Connected (Successful As Boolean)
   If Successful Then
      cmdConnect.Enabled=False
      cmdDisconnect.Enabled=True
      cmdCut.Enabled=True
      cmdESC.Enabled=True
      AOutputStream=ASocket.OutputStream
   End If
   Log(LastException)
End Sub

Sub cmdDisconnect_Click
   cmdConnect.Enabled=True
   cmdDisconnect.Enabled=False
   cmdCut.Enabled=False
   cmdESC.Enabled=False
   Log(LastException) 
   ASocket.Close
   Log(LastException) 
   AOutputStream=Null
End Sub
 
Top