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,562
Last edited:

MFX

Member
Licensed User
Longtime User
Thanks, that doesn't really get me much furthur though. :-(

Martin.
 

Gary Miyakawa

Active Member
Licensed User
Longtime User
Martin,

Send me a PM and I'll send you a really small Telnet pgm that I use as my "starter" program for telnet like apps...

Cheers,

GaryM
 

MFX

Member
Licensed User
Longtime User
Many thanks, PM on it's way. All I need is a "foot in the door".

Regards.
Martin.
 

schlossbauer

New Member
Licensed User
Longtime User
Transmit large data with buffer

Hello Erel,
I got a question according to your post with that server application example.
You wrote a function/routine which receives data over a buffer so that the data can be very large although the buffer is very small. There are lot of annoying things done in this dowhile-loop. Is it possible, (has basic4android the ability) to receive data just by doing something like calling a receive function, so that i dont have to care about all the buffer size- and file size- stuff like checking the size of the inputstream and counting the bytes, that are already received?
 

schlossbauer

New Member
Licensed User
Longtime User
Okay thanks a lot!
I just wrote my own serverapp in B4A and i built a client in C# and it works well.
But now i tried to build this client in B4A and it works while sending a small text (smaller as the buffer size) but can you post me an example how to transmit a text larger as the buffer? For example just some words in a string with a small buffer Dim buffer(2) As Byte?
That would be very helpful cause i dont know how to handle with the inputstream size and the code for piecewise filling/reading from the buffer.
Thanks a lot!
 

Wim213

New Member
Licensed User
Longtime User
Hi all,

I am a bit lost. Looking at this site for 2 days, I still find it difficult to use this library. What I am looking for is to connect to a server on another machine and be able to send and receive text through a TCP socket.

Unfortunantaly the examples I find are either a server to receive files, or a client that just receives info from a NTP server.

Where can I find the documentation that describes the events that can be fired ? In the examples I find the connected event, but once connected what is fired if you receive data on the socket ? Or do I use a timer and check every so often ? How can I send data through the outputstream method.

Thanks to anyone who can help me.

Wim.
 

hennemarc

Member
Licensed User
Longtime User
Hi Wim213,

this is exactly what I am looking for. Just sending a simple string to a TCP server. That's it. But so far I am fighting with the tutorial without success. Do you have meanwhile the information you needed? If yes, would you please share the outcome, so that I can profit from that?

Regards,

hennemarc
 

krsrn

Member
Licensed User
Longtime User
Help!

I m having difficulty getting the example to work. Although I have managed to get it on to my device. When I run the desktop Application I get errors - No Connection cpuld be made, the target machine actively refused it 127.0.0.1:5007.

Any help please?
 

krsrn

Member
Licensed User
Longtime User
Sorry Erel I m unsure of what you mean.

Do you mean within the coding execute the statement to connect to 127.0.0.1?
 

berder

New Member
Licensed User
Longtime User
hi. Please tell me what could be the problem and wrote a simple program for sending messages. android with a computer message comes, and when I try to send from your computer, the application for Android-locked with an unknown error.:confused:
 
Status
Not open for further replies.
Top