Interprocess communication with the Network library

Erel

B4X founder
Staff member
Licensed User
Longtime User
One way to communicate between two processes is to open a network socket on each process and use the local host IP (127.0.0.1) to send and receive messages.
One application will play the server role and the other will be the client.
IPC1 code (server):
B4X:
Sub App_Start
    Form1.Show
    TimeFormat("hh:mm:ss")
    client.New1
    server.New1(55555)
    server.Start
    tmrWaitForOtherApp.Enabled = true
End Sub

Sub Button1_Click
    bin.WriteString("Time: " & Time(Now) & " Hello from IPC1")
End Sub

Sub tmrWaitForOtherApp_Tick
    If server.Pending Then
        client.Value = server.Accept
        bin.New1(client.GetStream,false)
        tmrWaitForOtherApp.Enabled = false
        tmrWaitForData.Enabled = true
        Button1.Enabled = true
    End If
End Sub

Sub tmrWaitForData_Tick
    If client.DataAvailable Then
        textBox1.Text = bin.ReadString
    End If
End Sub
The server uses two timers. The first one - tmrWaitForOtherApp waits for the other application to connect.
The second timer - tmrWaitForData checks if there is data waiting to be read.

IPC2 code (client side):
B4X:
Sub App_Start
    Form1.Show
    TimeFormat("hh:mm:ss")
    client.New1
    Do Until ConnectToServer = true
        If Msgbox("Please first run IPC1.exe." & crlf _  
            & "Try again?","",cMsgboxYesNo) = cNo Then AppClose
    Loop
End Sub

Sub ConnectToServer
    ErrorLabel(NoServer)
    client.Connect("127.0.0.1",55555)
    bin.New1(client.GetStream,false)
    tmrWaitForData.Enabled = true
    Button1.Enabled = true
    Return true
NoServer:
    Return false
End Sub
Sub Button1_Click
    bin.WriteString("Time: " & Time(Now) & " Hello from IPC2")
End Sub


Sub tmrWaitForData_Tick
    If client.DataAvailable Then
        textBox1.Text = bin.ReadString
    End If
End Sub
The client side tries to connect with the server. If connection failed (most probably because IPC1 is not running) then it shows a message and tries to connect again.
The client also uses a timer to check for available data.
The source code and compiled executables are attached.
 

Attachments

  • IPC.zip
    31.7 KB · Views: 472
Top