Socket communication, PC Server, Android Client


Active Member
Licensed User
Longtime User
Hello there. I am trying to do simple Socket communication between Android and a .NET-based Socket Server. With the Server, I found the following code(I have to do some corrections but I gave more attention to the B4A part and left it unmodified). What should be done is make the server listen all the time and stop only after a "STOP command is received:

Imports System.Net
Imports System.Text
Imports System.Net.Sockets

Module Module1

    Sub Main()
        ' Must listen on correct port- must be same as port client wants to connect on.
        Const ipAddress As String = ""
        Const portNumber As Integer = 8000
        Dim tcpListener As New TcpListener(portNumber)
        Console.WriteLine("Waiting for connection...")
            'Accept the pending client connection and return 
            'a TcpClient initialized for communication. 
            Dim tcpClient As TcpClient = tcpListener.AcceptTcpClient()
            Console.WriteLine("Connection accepted.")
            ' Get the stream
            Dim networkStream As NetworkStream = tcpClient.GetStream()
            ' Read the stream into a byte array
            Dim bytes(tcpClient.ReceiveBufferSize) As Byte
            networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
            ' Return the data received from the client to the console.
            Dim clientdata As String = Encoding.ASCII.GetString(bytes)
            Console.WriteLine(("Client sent: " + clientdata))
            Dim responseString As String = "Connected to server."
            Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(responseString)
            networkStream.Write(sendBytes, 0, sendBytes.Length)
            Console.WriteLine(("Message Sent /> : " + responseString))
            'Any communication with the remote client using the TcpClient can go here.
            'Close TcpListener and TcpClient.
        Catch e As Exception
        End Try
    End Sub

End Module

I read the Network Tutorial by Erel which shows exactly what I need - the Android device acts like a client and connects to the Server. Also, I noticed Erel recommends that we use AsyncStreams to prevent our UI from blocking.

The code below is actually directly Erel's one with some modifications I tried to make but they were unsuccessful:

Actually what I want to achieve is:
  • Start the .NET Server
  • Connect from the Android client
  • Start sending commands to the Server from the Android. Something like SET1, SET2, RST1,RST2
  • The Server will do further actions based on the received "code"

My problem is that in Erel's AsyncStream tutorial, the Android device is playing the role of the Server, opposed to the Network tutorial where it is a client.

Here is the place to say I was able to see "Connected" on the Server but as stated in the Network tutorial, the UI hangs and the application is forced closed eventually.

I am still not confident enough with Sockets!

Sub Process_Globals
    Dim AStreams As AsyncStreams
    Dim Server As ServerSocket
    Dim Socket1 As Socket
End Sub
Sub Globals
    Dim EditText1 As EditText
   Dim lbStatus, lbResult As Label
End Sub
Sub Activity_Create(FirstTime As Boolean)
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
    sb.Append(tr.ReadLine) 'read at least one line
    Do While tr.Ready
    Msgbox("Time received: " & CRLF & sb.ToString, "")
End Sub

'press on the Done button to send text
Sub EditText1_EnterPressed
    If AStreams.IsInitialized = False Then Return
    If EditText1.Text.Length > 0 Then
        Dim buffer() As Byte
        buffer = EditText1.Text.GetBytes("UTF8")
        Log("Sending: " & EditText1.Text)
    End If
End Sub

Sub Activity_Pause(UserClosed As Boolean)
    If UserClosed Then
    End If
End Sub
Sub btnConnect_Click
  '  Try
   Socket1.Connect("" , 8000, 20000)
   'Dim sent As String
   'sent = "Hello Server"
    'Dim buffer() As Byte
       ' buffer = sent.GetBytes("UTF8")
   'End Try
End Sub

Sub btnDisconnect_Click
End Sub

Sub ChangeStatus(thetype As String)
If(thetype = "connect") Then
lbStatus.Text = "Connected to Server!"
Else If(thetype = "disconnect") Then
lbStatus.Text = "Disconnected"
Else If(thetype = "fail") Then
lbStatus.Text = "Unable to connect to Server!"
End If
End Sub

Can anyone throw some light how do achieve it? As you see, I am posting the code which proves I've tried myself and now need help.

P.S I know my code doesn't send anything to the Server(it's not implemented) but that's just one of the things I am looking help for, I dunno how to do it.
Last edited: