Android Tutorial Android Network Tutorial

Discussion in 'Tutorials & Examples' started by Erel, Dec 21, 2010.

Thread Status:
Not open for further replies.
  1. Erel

    Erel Administrator Staff Member Licensed User

    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.

    Sub Process_Globals
    Dim Socket1 As Socket
    End Sub

    Sub Globals

    End Sub

    Sub Activity_Create(FirstTime As Boolean)
    "" , 1320000)
    End Sub

    Sub Socket1_Connected (Successful As Boolean)
    If Successful = False Then
    Msgbox(LastException.Message, "Error connecting")
    End If
    Dim tr As TextReader
    Dim sb As StringBuilder
    'read at least one line
        Do While tr.Ready
    Msgbox("Time received: " & CRLF & sb.ToString, "")
    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).


    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.
    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:
    Sub Activity_Resume
    End Sub

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

    Sub ServerSocket1_NewConnection (Successful As Boolean, NewSocket As Socket)
    If Successful Then
            Socket1 = NewSocket
            Timer1.Enabled = 
            InputStream1 = Socket1.InputStream
            OutputStream1 = Socket1.OutputStream
    Msgbox(LastException.Message, "Error connecting")
    End If
    '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.

    Attached Files:

    Last edited: Feb 5, 2016
    Milton FS Santos and lemonisdead like this.
  2. schimanski

    schimanski Well-Known Member Licensed User

    Hello Erel,

    thanks for this network-lib. Together with agrahams threading-lib, my network-apps are running as good as under basic4ppc. :icon_clap: Respect!!

    But I have two questions:

    -I checked if the connection is successful with the following code, but when the connection isn't successful, I get an error, that the socket is not connected. It seems, that 'Successful' always is true:confused: I never get the msgbox 'not connected'.

    -Is there a way to jump to the android-settings to switch the network on, like jumping to the GPS-settings as

    Sub Socket1_Connected (Successful As Boolean)
    If Successful Then
    Msgbox("Not Connected!","")
    End If
    End Sub
  3. agraham

    agraham Expert Licensed User

  4. Erel

    Erel Administrator Staff Member Licensed User

    There is a bug in Network 1.00 regarding the successful flag. Fixed now:

    Using the Phone library you can create this Intent:
    Dim i As Intent
    BTW, Socket.Connect and ServerSocket.Listen are handled internally in the background and will not block your program.
  5. schimanski

    schimanski Well-Known Member Licensed User

    Thanks, works great!!!
  6. moster67

    moster67 Expert Licensed User

    Does the library support UDP?
  7. Erel

    Erel Administrator Staff Member Licensed User

    No. Only TCP.
  8. CallamMcMillan

    CallamMcMillan New Member

    Can you initialise the socket object with an IPv6 address, and does android support WLAN connections to IPv6 only networks?
  9. Erel

    Erel Administrator Staff Member Licensed User

    Yes. You can pass an IPv6 address as the host parameter.
    According to the documentation it is supported. I haven't tested it myself.
  10. James Moxham

    James Moxham Member Licensed User

    After exploring many options, I wonder if this might be the key to interfacing an Android with the real world?

    (For those of us with the cheaper pads that don't have bluetooth).

    After much searching, I think this might be the cheapest way to convert cat5 to serial WIZnet Serial-to-Ethernet Gateway - WIZ110SR - SparkFun Electronics (well, not quite as the cheapest probably involves buying a W5100 chip and soldering it, but the pins are 0.2mm apart!).

    If you can get data to serial, there are many devices that can convert real world data into serial eg picaxe, arduino, propeller.

    I do like the simple software interface for these sockets. Sure is a lot easier than trying to write a TCP stack.
  11. Erel

    Erel Administrator Staff Member Licensed User

  12. moster67

    moster67 Expert Licensed User

  13. ZJP

    ZJP Active Member Licensed User

    Thx. :)
  14. MFX

    MFX Member Licensed User

    Say I have one of these :-
    WiPort - 802.11b Wireless - 802.11g Wireless - Lantronix

    As a wireless to serial bridge with the serial data going to/from a microcontroller. Can the Android device talk directly to the Wiport or do I have to connect through an access point?

  15. Erel

    Erel Administrator Staff Member Licensed User

    Android doesn't support adhoc connections. It seems like you will need to connect through an access point.
  16. MFX

    MFX Member Licensed User

    Thanks although I've recently seen references that suggest that Ad hoc is available from 2.2 onwards. Not sure what's involved in getting it working though?
  17. MFX

    MFX Member Licensed User

    Does anyone know of any example code for setting up Telnet connection between two devices? Basically I simply want to send text between two devices.

  18. Erel

    Erel Administrator Staff Member Licensed User

  19. MFX

    MFX Member Licensed User

    Thanks, I've been a bit busy so it's been a while before I could try this. I've looked at the examples and am still confused. It looks like the Asyncstreams example is for when the device acts as a server is this correct? And the network examples seem to be both server and client? To simplify what I want to do :-

    Android device is the Client
    Android device connects to IP address (e.g. Port 23 (telnet)
    Telnet software on PC (in this case Realterm set o server:telnet) is the server.
    If connection is successful then I send text between the two devices.

    I've managed to successfully connect to the PC but unfortunately because there's only a few examples around I'm having trouble getting my head round what I need to do next. What I think I need is an Asyncstreams client example?

  20. Erel

    Erel Administrator Staff Member Licensed User

    AsyncStreams is not related to a server or client application. It is just another option for working with input/output streams.
Thread Status:
Not open for further replies.
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice