Android Tutorial Android Network Tutorial

Status
Not open for further replies.
This is an old tutorial. All new implementations of network solutions should be based on AsyncStreams.

The Network library allows you to communicate over TCP/IP with other computers or devices.
The Network library contains two objects. Socket and ServerSocket.
The Socket object is the communication endpoint. Reading and writing are done with Socket.InputStream and Socket.OutputStream.

ServerSocket is an object that listens for incoming connections. Once a connection is established an event is raised and a socket object is passed to the event sub. This socket will be used to handle the new client.

Client application
Steps required:
- Create and initialize a Socket object.
- Call Socket.Connect with the server address.
- Connection is done in the background. The Connected event is raised when the connection is ready or if it failed.
- Communicate with the other machine using Socket.InputStream to read data and Socket.OutputStream to write data.

Server application
Steps required:
- Create and initialize a ServerSocket object.
- Call ServerSocket.Listen to listen for incoming connections. This happens in the background.
- Once a connection is established the NewConnection event is raised and a Socket object is passes.
- Call ServerSocket.Listen if you want to accept more connections.
- Using the Socket object received, communicate with the client.

We will see two examples.
The first example connects to a time server and displays the current date and time as received from the server.

B4X:
Sub Process_Globals
    Dim Socket1 As Socket
End Sub

Sub Globals

End Sub

Sub Activity_Create(FirstTime As Boolean)
    Socket1.Initialize("Socket1")
    Socket1.Connect("nist1-ny.ustiming.org" , 13, 20000)
End Sub

Sub Socket1_Connected (Successful As Boolean)
    If Successful = False Then
        Msgbox(LastException.Message, "Error connecting")
        Return
    End If
    Dim tr As TextReader
    tr.Initialize(Socket1.InputStream)
    Dim sb As StringBuilder
    sb.Initialize
    sb.Append(tr.ReadLine) 'read at least one line
    Do While tr.Ready
        sb.Append(CRLF).Append(tr.ReadLine)
    Loop
    Msgbox("Time received: " & CRLF & sb.ToString, "")
    Socket1.Close
End Sub
We are creating a new socket and trying to connect to the server which is listening on port 13.
The next step is to wait for the Connected event.
If the connection is successful we create a TextReader object and initialize it with Socket1.InputStream. In this case we want to read characters and not bytes so a TextReader is used.
Calling tr.ReadLine may block. However we want to read at least a single line so it is fine.
Then we read all the other available lines (tr.Ready means that there is data in the buffer).

network_1.png


In the second application we will create a file transfer application, that will copy files from the desktop to the device.
The device will use a ServerSocket to listen to incoming connections.
Once a connection has been made, we will enable a timer. This timer checks every 200ms whether there is any data waiting to be read.

The file is sent in a specific protocol. First the file name is sent and then the actual file.
We are using a RandomAccessFile object to convert the bytes read to numeric values. RandomAccessFile can work with files or arrays of bytes, we are using the later in this case.
RandomAccessFile can be set to use little endian byte order. This is important here as the desktop uses this byte order as well.

The desktop example application was written with Basic4ppc.
Once connected the user selects a file and the file is sent to the device which saves it under /sdcard/android.
Both applications are attached.

Some notes about the code:
- The server is set to listen on port 2222.
The server displays its IP when it starts. The desktop client should use this IP address when connecting to a real device (this IP will not work with the emulator).
However if you work with the emulator or if your device is connected to the computer in debug mode you can use 'adb' to forward a desktop localhost port to the device.
This is done by issuing "adb forward tcp:5007 tcp:2222"
Now in the client code we should connect to the localhost ip with port 5007.
B4X:
Client.Connect("127.0.0.1", 5007)
Again if you are testing this application in the emulator you must first run this adb command. Adb is part of the Android SDK.

- Listening to connections:
B4X:
Sub Activity_Resume
        ServerSocket1.Listen
End Sub

Sub Activity_Pause (UserClosed As Boolean)
    If UserClosed Then
        Timer1.Enabled = False
        Socket1.Close
        ServerSocket1.Close 'stop listening
    End If
End Sub

Sub ServerSocket1_NewConnection (Successful As Boolean, NewSocket As Socket)
    If Successful Then
        Socket1 = NewSocket
        Timer1.Enabled = True
        InputStream1 = Socket1.InputStream
        OutputStream1 = Socket1.OutputStream
        ToastMessageShow("Connected", True)
    Else
        Msgbox(LastException.Message, "Error connecting")
    End If
    ServerSocket1.Listen 'Continue listening to new incoming connections
End Sub
In Sub Activity_Resume (which also called right after Activity_Create) we call ServerSocket.Listen and start listening to connections. Note that you can call this method multiple times safely.
In Sub Activity_Pause we close the active connection (if there is such a connection) and also stop listening. This only happens if the user pressed on the back key (UserClosed = True).
The ServerSocket will later be initialized in Activity_Create.

The server side application can handle new connections. It will just replace the previous connection with the new one.
The desktop client example application doesn't handle broken connections. You will need to restart it to reconnect.

Edit: It is recommended to use the new AsnycStreams object instead of polling the available bytes parameter with a timer. Using AsyncStreams is simpler and more reliable.
 

Attachments

  • NetworkExample.zip
    23.7 KB · Views: 7,691
Last edited:

krsrn

Member
Licensed User
Longtime User
Lets start from the beginning.
Why do you need to connect to an IP in ServerSocket1_NewConnection?
The socket is already connected.

Connecting within the Active_Create Screen caused no connection to be established at all. Although it compiled the connected status was not shown.
 

krsrn

Member
Licensed User
Longtime User
I have indeed started with the orginal Example.

Below is my Create Function and Connected Function. However the connection is refused. I thought maybe it is an issue with the port being blocked by my Firewall however upon trying this still no joy.

Sub Activity_Create(FirstTime As Boolean)
If FirstTime Then
Timer1.Initialize("Timer1", 200)
File.MakeDir(File.DirRootExternal, "android")
End If

Socket1.Initialize("Socket1")
Socket1.Connect("127.0.0.1", 5007,0)

Activity.LoadLayout("1")
End Sub

Sub Socket1_Connected (Successful As Boolean)

If Successful = False Then
Msgbox(LastException.Message, "Error connecting")
Return
Else
ToastMessageShow("Connected", True)
End If

Socket1.Close

End Sub
 

krsrn

Member
Licensed User
Longtime User
Can you clarify please?

My understanding was that if I specify the connection 127.0.0.1. It will create a loop back connection therefore allowing me to connect to my desktop machine from my device.

I will then be able to send a file from the server application running on my desktop machine to be recieved from my device.

The server application is listening on for connections on 127.0.0.1, 5007 therefore if I do not make a connection in the coding where do I make the connection?
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
The device is not part of the desktop. 127.0.0.1 will point to the device itself.
You should find the server IP and connect to it. Note that it is easier to have the device act as the server. Windows firewall will not allow you to make incoming connections without changing the configuration.

You should also check B4AServer it solves many of these problems.
 

Amateurtje

Member
Licensed User
Longtime User
simple transfer

I have been looking through this thread but I do not seem to get it. I actually want to do some very simple thing: Send to Ipadress 192.168.1.20 with port 1001 a "1 12". The ""1" is the adres and the 12 is the value I want to send which can vary.
Secondly, After sending "50 50" (see above) the same Ip adres and port starts to send a lot of data. This string of data I need to have to do some further stuff.

Who can give me a start?

With the socket I do not see how to catch the incoming stream or how to send a stream.

Sorry, I am very , very new to B4Android. I have a little VB background.
 

Amateurtje

Member
Licensed User
Longtime User
hi Erel,

It is true, I am still a unlicensed user while I want to see if I can do what I need to do.
The trial version is indeed very limited in which it is impossible to evaluate the package to see if it can do what it is supposed to.
For example a program like picbasic (which I bought after eval also) has a nice working trial version.
 
Last edited:

konisek

Member
Licensed User
Longtime User
reconnect

I succefully use:
B4X:
Sub Button1_Click 'connect
   Socket1.Initialize("Socket1")    'Set correct ServerIp  
   Socket1.Connect(EditText1.Text,EditText2.Text,3000)' IP, Port, Timeout
   ProgressDialogShow("Connecting...")
End Sub
and after running the code I disconnect with:
B4X:
Sub Button2_Click
   Socket1.Close   
End Sub

Then I want to connect over again but always get refused. The only way is to use:
B4X:
Sub Button4_click
ExitApplication
End Sub
and then start the app over. Why can't I connect again?
 

konisek

Member
Licensed User
Longtime User
Sometimes it connects again immediately, sometimes even a 30 seconds pause does not help. I solved it by not disconnecting from the socket, (L)
 

rayzrocket

Member
Licensed User
Longtime User
Socket.ResolveHost vs. ABwifiinfo.SSID

Is SSID the same as 'host name'(used as input in socket.resolvehost(hostname)) ?? (sorry for the dumb question)

I would like to make a network connection (on Wifi) by first presenting the Android user with a list of connected Wifi network SSID(names) and then making an asyncstreams I/O connection via the socket.connect.
 

electro179

Active Member
Licensed User
Longtime User
I have two big problem

Hello

I have got 2 problems

1) With the udp socket.
The event PacketArrived doesn't work if the address ip is a broadcast address.
If I send a message from my pc to android in using 192.168.1.3 no problem
but the message will never come if the address is 192.168.1.255

2) I create a udpsocket in the activity but I'd like use this even socket in next activity. The event PacketArrived doesn't work in a other activity.
If I close the socketwith udpsocket.close I can't create again the socket with the even port.

have you a solution for these problem ?
 

electro179

Active Member
Licensed User
Longtime User
hi

sorry for duplicate message

1) if I send the some message but to a other pc. no problem

2) I create the socket with the service and the function Sub UDP_PacketArrived i also into service
 
Status
Not open for further replies.
Top