Android Question Sending data from app to another how?

camolas

Member
Licensed User
Longtime User
Hi,
Im using a python scrit to read incoming sms from a usb gsm modem ( for now i cant put to work in b4a ) in the py i have this to creat a " tunel"
B4X:
import sys
from socket import socket, AF_INET, SOCK_DGRAM

SERVER_IP   = '127.0.0.1'
PORT_NUMBER = 5000
SIZE = 1024
print ("Test client sending packets to IP {0}, via port {1}\n".format(SERVER_IP, PORT_NUMBER))

mySocket = socket( AF_INET, SOCK_DGRAM )

while True:
        mySocket.sendto('cool',(SERVER_IP,PORT_NUMBER))
sys.exit()

How can i "catch" the data to a b4a and display it?
Thankz
 
Last edited:

Straker

Active Member
Licensed User
Longtime User
First you have to check if the 'server' (the py script) is in listen mode. Can you give me the piece of the script code where you define and open the server socket? On the server socket the code must accept the incoming request for connection.
I don't see anything wrong in your B4A code, probably there is something in the py script.

Second, I assume your compiling and debugging with B4A bridge (the USB port is connected to the modem). Instead of using localhost (127.0.0.1) did you try to use the same Ip used by the bridge?
 
Upvote 0

camolas

Member
Licensed User
Longtime User
Hi,

Py script server:
B4X:
import sys
from socket import socket, AF_INET, SOCK_DGRAM

SERVER_IP   = '127.0.0.1'
PORT_NUMBER = 5000
SIZE = 1024
print ("Test client sending packets to IP {0}, via port {1}\n".format(SERVER_IP, PORT_NUMBER))

mySocket = socket( AF_INET, SOCK_DGRAM )

while True:
        mySocket.sendto('cool',(SERVER_IP,PORT_NUMBER))
sys.exit()

Im compiling and debugging with B4A bridge over wifi.

Thx
 
Upvote 0

Straker

Active Member
Licensed User
Longtime User
A socket connection is made with a client which connects to a server which is listening for connection. In your code it seems that both sides are clients...
I'll make some test and I'll be back in a couple of hours...
 
Upvote 0

Straker

Active Member
Licensed User
Longtime User
Try this code:

B4X:
Sub Process_Globals      
    'You need Network library (for sockets) and RandomAccessFile library (for Streams)
    Dim srvSocket As ServerSocket
    Dim clientSocket As Socket
    Dim SocStream As AsyncStreams  
End Sub


Sub Activity_Create(FirstTime As Boolean)
    srvSocket.Initialize (5000,"srvSocket")
    srvSocket.Listen 
    clientSocket.Initialize ("")
End Sub

Sub srvSocket_NewConnection(Successfull As Boolean , NewSocket As Socket )
    Log("Connection is " & Successfull)
    If Successfull Then
        clientSocket=NewSocket
        SocStream.Initialize(clientSocket.InputStream, clientSocket.OutputStream,"SocStream")
    End If   
End Sub

Sub SocStream_NewData (Buffer() As Byte)
    'Received new data
    Dim msg As String
    Dim cMsg As String       
    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
    Log("Received " & cMsg)
   
End Sub

This code is absolutely not good, is just "quick&dirty" for a test. Anyway, just test it and see if in the log you recive then 'cool' message from the py client.
 
Upvote 0

Straker

Active Member
Licensed User
Longtime User
Not even "Connection is False"? And same exception error?
 
Upvote 0

camolas

Member
Licensed User
Longtime User
is use other port "2277" change the port number on py and on b4a and dont work, my screen get black and thr log on b4a ide just gives
B4X:
(Intent) Intent { act=android.intent.action.MAIN flg=0x20000000 cmp=IanMcRV.SideWays/.main }
no extras
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
(Intent) Intent { act=android.intent.action.MAIN flg=0x20000000 cmp=IanMcRV.SideWays/.main }
no extras
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
 
Upvote 0

Straker

Active Member
Licensed User
Longtime User
ok, wait a moment.
I re-read the thread and I noticed (only now, sorry for this) that you have the socket open with SOCK_DGRAM which is UDP and not TCP.
SO, try to use SOCK_STREAM instead.
Second, I've noticed that it seems you have the python code BOTH for server and client socket, which is correct if is the python script that acts as server (but in my code was the B4A that acts as server).

Anyway, in your py-server - the piece of code where is the line
B4X:
print ("Test server listening on port {0}\n".format(PORT_NUMBER)
I don't see any mySocket.Listen(n) (where n is the max number of allowed connection, 1 is enough in your case)

But you say that you want to replace that part of code, so: who cares.

At this moment just replace SOCK_DGRAM with SOCK_STREAM and see what happens.

Just another question: are you sure the python client code works? Shoudn't it be something like:
mySocket = socket( AF_INET, SOCK_STREAM ) -> here I changed from UDP to TCP
MySocket.connect((HOST, PORT))
mySocket.send('cool')
- never see the sendto construct in python (maybe means connect + send...)
 
Upvote 0

camolas

Member
Licensed User
Longtime User
if i chang to SOCK_STREAM the py server dont work i cant get the sending report, yes py client works very well with py server

Thx
 
Upvote 0

Straker

Active Member
Licensed User
Longtime User
Wait a moment... you have just wrote that PY SERVER don't work... and I'm getting confused! In one of your first post you said that you want to replace the py-server with the B4A. My code works as SERVER and cannot connect to another server (of course, both are waiting listening, and nobody starts the connection).
So tell me: WHO IS THE SERVER? B4A or PY? If PY acts as server, if you want I can write a simple-stupid socket client in just a couple of minutes...
 
Upvote 0

Straker

Active Member
Licensed User
Longtime User
Ok, tomorrow I'll post a socket client example.
 
Upvote 0

Straker

Active Member
Licensed User
Longtime User
The code is something like this (note: I'm writing on an iPad not with a PC, so there may be some misspelling.)

B4X:
dim clientsocket as socket. ' in process-global
Dim SocStream as asyncstreams. 'In process.globals
 clientsocket.initialize("clientsocket") 'in activity–create

Clientsocket.Connect("127.0.0.1",5000,15000)  'in act.create

Sub Clientsocket_Connected(Connected As Boolean) As Boolean
   If Connected = true then
      Log("connected")
      Socstream.Initialize(Clientsocket.InputStream,Clientsocket.OutputStream,"SocStream")
   Else
       Log("not connected")
   EndIf
End Sub

'Add here the socstream_NewData sub from my previous example

It is not a very good example. You need to close the socket somewhere...
Tomorrow I'll post something better.
 
Upvote 0

Straker

Active Member
Licensed User
Longtime User
Upvote 0

camolas

Member
Licensed User
Longtime User
Hi,

I get from log "not connected" i put the code like this
B4X:
#Region  Project Attributes
    #ApplicationLabel: xx
    #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
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Dim clientsocket As Socket
    Dim SocStream 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.

End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    'Activity.LoadLayout("Layout1")
    clientsocket.initialize("clientsocket")
    clientsocket.Connect("127.0.0.1",5000,15000)

End Sub
Sub Clientsocket_Connected(Connected As Boolean) As Boolean
   If Connected = True Then
      Log("connected")
      SocStream.Initialize(clientsocket.InputStream,clientsocket.OutputStream,"SocStream")
   Else
       Log("not connected")
   End If
End Sub
Sub SocStream_NewData (Buffer() As Byte)
    'Received new data
    Dim msg As String
    Dim cMsg As String     
    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
    Log("Received " & cMsg)
 
End Sub
Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub
 
Upvote 0

Straker

Active Member
Licensed User
Longtime User
Did you change SOCK_DGRAM with SOCK_STREAM?
Anyway, what I don't really understand is the logic of yor python code.
In Python a socket server is someting like this:
B4X:
import socket

HOST = ''     # It means the local host
PORT = 5000 # the port port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))    # binding the socker
s.listen(1)   # Put the serve in listening mode, accepting only 1 connection at a time
conn, addr = s.accept()  # accept an incoming connection from the IP 'addr'. Conn is a new socket
   # that will be used for the data exchange. The server socket normally doesn't 
   # perform data exchage but only listen and accept/refuse incominq conn requests
print 'Connected by', addr  # Just a feedback
while 1:
    data = conn.recv(1024) # wait for some data
    if not data: break  # if no data, break
    conn.send(data)  # resend the same data (is an echo server, or you can conn.send('Hallo world')
conn.close()  #ok, close the connection (not the server)

In the code you say it acts as server I don't see the two basic operation performed by a socket server (accept the incoming connection and create the new socket for data exchange...)

Can you explain a little bit your python code? I really cannot understand which side acts as server (py or b4a) listening for incoming connection...
 
Upvote 0
Top