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:
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:
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!
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.
B4X:
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 = "127.0.0.1"
Const portNumber As Integer = 8000
Dim tcpListener As New TcpListener(portNumber)
tcpListener.Start()
Console.WriteLine("Waiting for connection...")
Try
'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.
tcpClient.Close()
tcpListener.Stop()
Console.WriteLine("exit")
Console.ReadLine()
Catch e As Exception
Console.WriteLine(e.ToString())
Console.ReadLine()
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!
B4X:
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)
Activity.LoadLayout("1")
Socket1.Initialize("Socket1")
End Sub
Sub Socket1_Connected (Successful As Boolean)
If Successful = False Then
Msgbox(LastException.Message, "Error connecting")
Return
End If
ChangeStatus("connect")
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
ChangeStatus("disconnect")
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")
AStreams.Write(buffer)
EditText1.SelectAll
Log("Sending: " & EditText1.Text)
End If
End Sub
Sub Activity_Pause(UserClosed As Boolean)
If UserClosed Then
Log("closing")
AStreams.Close
Socket1.Close
End If
End Sub
Sub btnConnect_Click
' Try
Socket1.Connect("192.168.11.6" , 8000, 20000)
'Dim sent As String
'sent = "Hello Server"
'Dim buffer() As Byte
' buffer = sent.GetBytes("UTF8")
'AStreams.Write(buffer)
'Catch
'ChangeStatus("fail")
'End Try
End Sub
Sub btnDisconnect_Click
AStreams.Close
Socket1.Close()
ChangeStatus("disconnect")
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: