Android Question How can I create tcp in Service?

Sinan Tuzcu

Well-Known Member
Licensed User
Longtime User
Hello,

i programming a TCP/IP communication from my Phone between my PC.
It works very well.
But if I put the TCP/IP Part in a Service Modul, then dont works.
Why?

Who knows the answer for that issue?
Who can help me?

thanks in advance
Sinan
 

Sinan Tuzcu

Well-Known Member
Licensed User
Longtime User
Hi Erel,

this code is from me works very well this is without Service Modul:

B4X:
#Region Module Attributes
    #FullScreen: False
    #IncludeTitle: True
    #ApplicationLabel: TestTcpIp
    #VersionCode: 1
    #VersionName:
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
#End Region

'Activity module
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
        
    Dim Socket1 As Socket
    Dim AStreams As AsyncStreams
End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.
    Dim Wert01 As Long
    Dim Wert02 As Long
    Dim Wert03 As Long
    Dim Wert04 As Long
    
    Dim btnConnect As Button
    
    Dim lblMsg As Label
    Dim label1 As Label

    Private btnAN As Button
    Private btnAUS As Button
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("1")
    
    
    Socket1.Initialize("Socket1")
        
    
    If FirstTime = True Then
    
    End If
    
End Sub

Sub Activity_Resume
End Sub
Sub Activity_Pause (UserClosed As Boolean)
End Sub

Sub btnConnect_Click
    Select Case btnConnect.Text
        Case "Connect"
            btnConnect.Text = "Disconnect"
            Socket1.Initialize("Socket1")
            Socket1.Connect("192.168.178.29",2000,5000)
            btnConnect.Enabled = True
        Case "Disconnect"
            btnConnect.Text = "Connect"
            Socket1.Close
            AStreams.Close
            
            'ExitApplication
        Case Else
    End Select
End Sub

Sub Socket1_Connected(Connected As Boolean)
    If Connected = True Then
        ToastMessageShow("Connected",True)
        AStreams.Initialize(Socket1.InputStream,Socket1.OutputStream,"Astreams")
    Else
        ToastMessageShow("Server not available",True)
        AStreams.Close
        Socket1.Close
        btnConnect.Text = "Connect"
    End If
    btnConnect.Enabled = True
End Sub

Sub AStreams_NewData (Buffer() As Byte)
    Dim msg As String
    Dim cMsg As String
    
    msg = BytesToString(Buffer, 0, Buffer.Length, "UTF8")
    Dim unsignedi As Int
    Dim signedb As Byte
'   
'    msg = BytesToString(Buffer, 0, Buffer.Length, "ASCII")
'   
    For i = 0 To msg.Length -1
        signedb = Buffer(i)
        unsignedi = Bit.And(0xff, signedb)
        cMsg = cMsg & Chr(unsignedi)
    Next
    
    Dim msg_trennen() As String = Regex.Split("\|",msg)
    Select Case msg_trennen(0).Trim

        Case "34FirstConnect"   
            lblMsg.Text =  msg_trennen(1)
    End Select
            
            
    'Log(cMsg)
    'lblMsg.Text = " / " & msg.Length & " - " & msg
    label1.Text = cMsg
End Sub



private Sub btnAN_Click
    Wert01 = 255
    Wert02 = 255
    Wert03 = 255
    Wert04 = 255
    CallSub(Me, SchaltZustandSenden)
End Sub

private Sub btnAUS_Click
    Wert01 = 0
    Wert02 = 0
    Wert03 = 0
    Wert04 = 0
    CallSub(Me, SchaltZustandSenden)
End Sub

Private Sub SchaltZustandSenden()
    CallSub2(Me, "SEND_TO_DEVICE",  CreateMap("WERT1":WERT1, "WERT2":WERT2, "WERT3":WERT3, "WERT4":WERT4))
End Sub


#Region "Commandos"
private Sub SEND_TO_DEVICE(MAPE As Map)
    SendComando("1|" & MAPE.Get("WERT1") & "|" & MAPE.Get("WERT2") & "|" & MAPE.Get("WERT3") & "|" & MAPE.Get("WERT4") & CRLF)
End Sub
#End Region

Sub SendComando(msg As String)
    Dim Buffer() As Byte
    msg = msg & CRLF
    Buffer = msg.GetBytes("ISO-8859-1")
    AStreams.Write(Buffer)
    AStreams.Write2(Buffer,0,Buffer.Length)
End Sub


and your code can not create a connection with my Server- device.
Can you tell me, what is wrong in this code from your, I have changed something
I have removed the Server part, because i need only Client part.
Main:
B4X:
#Region  Project Attributes
    #ApplicationLabel: B4A Example
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Process_Globals
    
End Sub

Sub Globals
    Private edtIp As FloatLabeledEditText
    Private lblMyIp As Label
    Private btnConnect As Button
    Private lblStatus As Label
    Private edtAge As FloatLabeledEditText
    Private edtName As FloatLabeledEditText
    Private btnSend As Button

    
    Dim Wert01 As Long
    Dim Wert02 As Long
    Dim Wert03 As Long
    Dim Wert04 As Long
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("1")
    StartService(Starter)
End Sub

Sub Activity_Resume
    SetState
End Sub

Public Sub SetState
    'btnSend.Enabled = Starter.connected
    If Starter.connected Then
        btnConnect.Text = "Disconnect"
        lblStatus.Text = "Connected"
    Else
        btnConnect.Text = "Connect"
        lblStatus.Text = "Disconnected"
    End If
    lblMyIp.Text = "My ip: " & Starter.server.GetMyWifiIP
End Sub

Sub btnSend_Click
    Wert01 = 255
    Wert02 = 255
    Wert03 = 255
    Wert04 = 255
    CallSub(Me, SchaltZustandSenden)
End Sub

Sub btnConnect_Click
    If Starter.connected = False Then
        If edtIp.Text.Length = 0 Then
            ToastMessageShow("Please enter the server ip address.", True)
            Return
        Else
            CallSub2(Starter, "ConnectToServer", "192.168.178.29")
        End If
    Else
        CallSub(Starter, "Disconnect")
    End If
End Sub

Public Sub NewData (Buffer() As Byte)
    Dim msg As String
    Dim cMsg As String
    
    msg = BytesToString(Buffer, 0, Buffer.Length, "UTF8")
    Dim unsignedi As Int
    Dim signedb As Byte
'   
    '    msg = BytesToString(Buffer, 0, Buffer.Length, "ASCII")
'   
    For i = 0 To msg.Length -1
        signedb = Buffer(i)
        unsignedi = Bit.And(0xff, signedb)
        cMsg = cMsg & Chr(unsignedi)
    Next
    
    Dim msg_trennen() As String = Regex.Split("\|",msg)
    Select Case msg_trennen(0).Trim

        Case "34FirstConnect"   'ETH-REL32
            edtName.Text =  msg_trennen(1)
    End Select
            
            
    'Log(cMsg)
    'lblMsg.Text = " / " & msg.Length & " - " & msg
    edtAge.Text = cMsg
End Sub

Private Sub SchaltZustandSenden()
    CallSub2(Me, "SEND_TO_DEVICE",  CreateMap("WERT1":WERT1, "WERT2":WERT2, "WERT3":WERT3, "WERT4":WERT4))
End Sub



Sub Activity_Pause (UserClosed As Boolean)

End Sub


Service Modul:
B4X:
#Region  Service Attributes
    #StartAtBoot: False
    #ExcludeFromLibrary: True
#End Region

Sub Process_Globals
    Public connected As Boolean
    Private client As Socket
    Public server As ServerSocket
    Private astream As AsyncStreams
    Private const PORT As Int = 2000
    
End Sub

Sub Service_Create
    
    
End Sub


Sub Service_Start (StartingIntent As Intent)

End Sub

Public Sub ConnectToServer(Host As String)
    
    CloseExistingConnection
    Dim client As Socket
    client.Initialize("client")
    client.Connect(Host, PORT, 10000)
    Wait For Client_Connected (Successful As Boolean)
    If Successful Then
        astream.InitializePrefix(client.InputStream, False, client.OutputStream, "astream")
        UpdateState (True)
    Else
        
    End If
End Sub

Public Sub Disconnect
    CloseExistingConnection
End Sub

Sub CloseExistingConnection
    If astream.IsInitialized Then astream.Close
    If client.IsInitialized Then client.Close
    UpdateState (False)
End Sub

Sub UpdateState (NewState As Boolean)
    connected = NewState
    CallSub(Main, "SetState")
End Sub

Sub AStream_Error
    UpdateState(False)
End Sub

Sub AStream_Terminated
    UpdateState(False)
End Sub

Sub AStream_NewData (Buffer() As Byte)
    CallSub2(Main, "NewData", Buffer)
End Sub





private Sub SEND_TO_DEVICE(MAPE As Map)
    SendComando("1|" & MAPE.Get("WERT1") & "|" & MAPE.Get("WERT2") & "|" & MAPE.Get("WERT3") & "|" & MAPE.Get("WERT4") & CRLF)
End Sub


Sub SendComando(msg As String)
    Dim Buffer() As Byte
    msg = msg & CRLF
    Buffer = msg.GetBytes("ISO-8859-1")
    AStreams.Write(Buffer)
    AStreams.Write2(Buffer,0,Buffer.Length)
End Sub

'Return true to allow the OS default exceptions handler to handle the uncaught exception.
Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
    Return True
End Sub

Sub Service_Destroy

End Sub
 
Upvote 0

Sinan Tuzcu

Well-Known Member
Licensed User
Longtime User
Erel the Problem is, if I put the Network Part in a Service Modul, then can not connected with Server.
And without Service Modul it works very well.

My Question is, how can I create a Service Modul for TCP/IP Communication.
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…