Android Question TCP/IP Server Client ServerSocket AsyncStreams

rtek1000

Active Member
Licensed User
Longtime User
Server:

B4X:
#Region Module Attributes
    #FullScreen: False
    #IncludeTitle: True
    #ApplicationLabel: Server
    #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 Socket2 As Socket
   
    Dim ServerSocket1 As ServerSocket

    Dim AStreamsServer 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 defaultServerPort As Int = 8080

    Private btnServerSend As Button

    Private lblServerLog As Label
    Private lblConnect As Label
End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Dim t As String
   
    Activity.LoadLayout("1")
   
    lblConnect.Text = ServerSocket1.GetMyIP
   
    ServerSocket1.Initialize(defaultServerPort,"ServerSocket1")
    ServerSocket1.Listen
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub ServerSocket1_NewConnection (Successful As Boolean, NewSocket As Socket)
    If Successful Then
        lblServerLog.Text = DateTime.Now & ": " & "Client Connected" & CRLF & lblServerLog.Text
        'ToastMessageShow("Connected_Client", False)
        Socket1 = NewSocket
        AStreamsServer.Initialize(Socket1.InputStream, Socket1.OutputStream, "AStreamsServer")
    Else
        ToastMessageShow(LastException.Message, True)
    End If
    ServerSocket1.Listen
End Sub

Sub AStreamsServer_NewData (Buffer() As Byte)
    Dim msg As String
    msg = BytesToString(Buffer, 0, Buffer.Length, "UTF8")
    lblServerLog.Text = DateTime.Now & ": " & msg & " " & lblServerLog.Text
    'ToastMessageShow(msg, False)
    Log(msg)
End Sub

Sub AStreamsServer_Error
    ToastMessageShow(LastException.Message, True)
End Sub

Sub SendMessage
    Dim str As String
    str = "Test"
    AStreamsServer.Write(str.GetBytes("UTF8"))
End Sub

Sub btnServerSend_Click
    SendMessage
End Sub


Client:

B4X:
#Region Module Attributes
    #FullScreen: False
    #IncludeTitle: True
    #ApplicationLabel: Client
    #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 Socket2 As Socket
    Dim ServerSocket1 As ServerSocket

    Dim AStreamsClient As AsyncStreams
   
    Dim timer1 As Timer
   

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 lblConnect As Label
    Dim btnConnect As Button

    Private btnClientSend As Button

    Private lblClientLog As Label
    Private lblServerLog As Label
    Private etServerIP As EditText
    Private etServerPort As EditText
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("1")
   
    lblConnect.Text = ServerSocket1.GetMyIP
   
    timer1.Initialize("timer1", 1000)
   
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub timer1_tick()
    If Socket2.Connected = False Then
        timer1.Enabled = False
        lblClientLog.Text = DateTime.Now & ": " & "Disconnected!" & CRLF & lblClientLog.Text
    End If
End Sub

Sub Socket2_Connected(Connected As Boolean)As Boolean
    If Connected = True Then
        ToastMessageShow("Connected",True)
       
        lblClientLog.Text = DateTime.Now & ": " & "Connected!" & CRLF & lblClientLog.Text
        AStreamsClient.Initialize(Socket2.InputStream,Socket2.OutputStream,"AStreamsClient")
       
        timer1.Enabled = True
    Else
        ToastMessageShow("Server not available",True)
       
        lblClientLog.Text = DateTime.Now & ": " & "Server not available" & CRLF & lblClientLog.Text
        btnConnect.Text = "Connect"
    End If

End Sub

Sub AStreamsClient_NewData (Buffer() As Byte)
    Dim msg As String
    Dim cMsg As String

    Dim unsignedi As Int
    Dim signedb As Byte
   
    msg = BytesToString(Buffer, 0, Buffer.Length, "ASCII")
    lblClientLog.Text = DateTime.Now & ": " & msg & CRLF & lblClientLog.Text
    Log(msg)
   
End Sub

Sub AStreamsServer_Error
    ToastMessageShow(LastException.Message, True)
End Sub

Sub SendData(msg As String)
    Dim Buffer() As Byte
   
    Buffer = msg.GetBytes("UTF8")
    AStreamsClient.Write(Buffer)
    AStreamsClient.Write(Array As Byte(10))
    AStreamsClient.Write(Array As Byte(13))

End Sub

Sub btnConnect_Click
    Select Case btnConnect.Text
        Case "Connect"
            btnConnect.Text = "Disconnect"
            Socket2.Initialize("Socket2")
           
            Socket2.Connect(etServerIP.Text,etServerPort.Text,5000)
        Case "Disconnect"
            btnConnect.Text = "Connect"
            Socket2.Close
           
        Case Else
    End Select
End Sub

Sub btnClientSend_Click
    Dim msg As String
   
    msg = "Teste"
    SendData(msg)
End Sub


Based on posts:
https://www.b4x.com/android/forum/threads/tcp-connection-with-vb6-app.9612/#post-74777

https://www.b4x.com/android/forum/threads/android-network-tutorial.7001/

https://www.b4x.com/android/help/randomaccessfile.html#asyncstreams

https://www.b4x.com/android/forum/threads/server-connection-lost-serversocket-sql.77134/#post-492095
 

Attachments

  • TestTcpIpServer.zip
    8.4 KB · Views: 740
  • TestTcpIpClient.zip
    8.8 KB · Views: 839

Star-Dust

Expert
Licensed User
Longtime User
good job. On the server I would have preferred to put the clutch door in a service so you can work in the background
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Upvote 0

Star-Dust

Expert
Licensed User
Longtime User
Erel is always careful. You can not do it under your nose :D:D:D
 
Upvote 0

rtek1000

Active Member
Licensed User
Longtime User
Well, I do not know what happens, but if I initialize ServerSocket only once, I can only connect to it for the first time, so the socket can not find the server anymore if it disconnects and tries to connect again.

I tested this on Android 2.3.6 and also on Android 6, in both the symptom is the same.

Client: [Server not available]
B4X:
Sub Activity_Create(FirstTime As Boolean)
    Socket2.Initialize("Socket2") ' <----------------------------------------- initialize ServerSocket once
End Sub

Sub btnConnect_Click
    Select Case btnConnect.Text
        Case "Connect"
            btnConnect.Text = "Disconnect"
            'Socket2.Initialize("Socket2")   ' <----------------------------------------- No initialize ServerSocket again
            Socket2.Connect(etServerIP.Text,etServerPort.Text,5000)
        Case "Disconnect"
            btnConnect.Text = "Connect"
            Socket2.Close
        Case Else
    End Select
End Sub

Client: [Connected!]
B4X:
Sub btnConnect_Click
    Select Case btnConnect.Text
        Case "Connect"
            btnConnect.Text = "Disconnect"
            Socket2.Initialize("Socket2")   ' <----------------------------------------- initialize ServerSocket again
            Socket2.Connect(etServerIP.Text,etServerPort.Text,5000)
        Case "Disconnect"
            btnConnect.Text = "Connect"
            Socket2.Close
        Case Else
    End Select
End Sub
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Upvote 0

rtek1000

Active Member
Licensed User
Longtime User
Ok thanks, in your example, the socket is being initialized every time the button is clicked, so it should not be wrong this in my code.
What I saw differently is that it is closing the socket if it is already open.

B4X:
Private client As Socket
...
If client.IsInitialized Then client.Close

I already added "AsyncStreams_Terminated" and "handle all communication in a service"

It's good to have feedback on the correct use of the code
 
Upvote 0
Top