Android Question AsyncStreams

VincenzoD

Member
Hello Everyone

I'm sorry for question, i would like to build Android client application that it make comunications and share messages with VB.net software.
When i tried to build android App i had problem to declare AsyncStreams variables.
My question is, i need to download library for it?
If yes, someone know where i can find and download it?

Thanks a lot for any Help.
 

VincenzoD

Member
@Erel I tryed to follow Your Example to use with my Vb.net application, the connection is fine but i have got problem to share messages.

When i try to send msg to server, no message appear

When i try to send msg to Client, the connection will be interrupted

Did you help me to solve this problem? I put my Vb.net program and B4A program here

VB.net program:

Imports System.Net
Imports System.Net.Sockets
Imports System.IO


Public Class Form1
Private client As TcpClient
Public STR As StreamReader
Public STW As StreamWriter
Public receive As String
Public receiveAsync As String
Public texttosend As String


Public Sub New()

' Chiamata richiesta dalla finestra di progettazione.
InitializeComponent()

' Aggiungere le eventuali istruzioni di inizializzazione dopo la chiamata a InitializeComponent().
Dim localIP As IPAddress() = Dns.GetHostAddresses(Dns.GetHostName)
For Each address As IPAddress In localIP
If address.AddressFamily = AddressFamily.InterNetwork Then
ServerIPTextBox.Text = address.ToString()
End If
Next
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
RadioButton1.Checked = True
End Sub

Private Sub StartButton_Click(sender As Object, e As EventArgs) Handles StartButton.Click
If ServerIPTextBox.Text = "" Or ServerPort.Text = "" Then
MsgBox("Attenzione! Inserire indirizzo IP o la porta !")
Else
Dim listener As New TcpListener(IPAddress.Any, Integer.Parse(ServerPort.Text))
listener.Start()
client = listener.AcceptTcpClient()
STR = New StreamReader(client.GetStream())
STW = New StreamWriter(client.GetStream())
STW.AutoFlush = True
BackgroundWorker1.RunWorkerAsync()
BackgroundWorker2.WorkerSupportsCancellation = True
End If


End Sub

Private Sub ConnectButton_Click(sender As Object, e As EventArgs) Handles ConnectButton.Click
client = New TcpClient
Dim IPEnd As New IPEndPoint(IPAddress.Parse(ClientIP.Text), Integer.Parse(ClientPort.Text))
Try

client.Connect(IPEnd)

If (client.Connected) Then
ChatScreenTextBox.AppendText(" Connesso al server " + Environment.NewLine)
STR = New StreamReader(client.GetStream())
STW = New StreamWriter(client.GetStream())
STW.AutoFlush = True
BackgroundWorker1.RunWorkerAsync()
BackgroundWorker2.WorkerSupportsCancellation = True
End If

Catch ex As Exception
MessageBox.Show(ex.Message.ToString)
End Try
End Sub

Private Async Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
While (client.Connected)
Try
receive = STR.ReadLine
receiveAsync = Await STR.ReadLineAsync
Me.ChatScreenTextBox.Invoke(New MethodInvoker(Function()
ChatScreenTextBox.AppendText("YOU: " + receive + Environment.NewLine)
End Function))
receive = ""
Catch ex As Exception
MessageBox.Show(ex.Message.ToString)
End Try
End While
End Sub

Private Sub BackgroundWorker2_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker2.DoWork
If (client.Connected) Then
STW.WriteLine(texttosend)
'STW.WriteLineAsync(texttosend)
Me.ChatScreenTextBox.Invoke(New MethodInvoker(Function()
ChatScreenTextBox.AppendText("ME: " + texttosend + Environment.NewLine)
End Function))
Else
MessageBox.Show("Sending Failed")
End If
BackgroundWorker2.CancelAsync()

End Sub

Private Sub SendButton_Click(sender As Object, e As EventArgs) Handles SendButton.Click
If (MessageTextBox.Text <> "") Then
texttosend = MessageTextBox.Text
BackgroundWorker2.RunWorkerAsync()
End If
MessageTextBox.Text = ""
End Sub

Private Sub RadioButton1_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton1.CheckedChanged
GroupBox1.Enabled = True
GroupBox2.Enabled = False
End Sub

Private Sub RadioButton2_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton2.CheckedChanged
GroupBox1.Enabled = False
GroupBox2.Enabled = True
End Sub
End Class

and B4A program:

#Region Project Attributes
#ApplicationLabel: B4A Example
#VersionCode: 1
#VersionName:
'SupportedOrientations possible values: unspecified, landscape or portrait.
#SupportedOrientations: unspecified
#CanInstallToExternalStorage: False
#End Region

#Region Activity Attributes
#FullScreen: False
#IncludeTitle: False
#End Region

' B4A - Basic4Android
' Programma Android
' Utilizza la libreria Socket per comunicare con l'applicazione Visual Basic sul PC


Sub Process_Globals
'These global variables will be declared once when the application starts.
'These variables can be accessed from all modules.
Private xui As XUI
Public socket As Socket
Private isconnected As Boolean
Private astream As AsyncStreams
Private ser As B4XSerializator
Type MyMessage (text As String)

'
End Sub

Sub Globals
'These global variables will be redeclared each time the activity is created.
'
Private EditTextIP As EditText
Private EditTextPORT As EditText
Private BtnConnetti As Button
Private LblDiscussione As Label
Private BtnInvia As Button
Private LbLog As Label
Private EditTextSender As EditText
'
End Sub

Sub Activity_Create(FirstTime As Boolean)
Activity.LoadLayout("Layout")
End Sub


Sub Activity_Resume
' Connessione al server
End Sub

Sub Activity_Pause (UserClosed As Boolean)
'
End Sub

Private Sub SetState (Connected As Boolean)
isconnected=Connected
'
If isconnected Then
LbLog.Text="State : Connected"
Else
LbLog.Text="State : Disconnected"
End If
'
End Sub

Private Sub BtnConnetti_Click
Dim IpAddress As String
'Dim Port As Int
SetState(False)
'
IpAddress=EditTextIP.Text
'Port=EditTextPORT.Text
'
'
If IpAddress="" Then
MsgboxAsync(" Destination IP cannot be empty !!! ", "")
Else
If astream.IsInitialized Then
astream.Close
End If
'
If socket.IsInitialized Then
socket.Close
End If
'
socket.Initialize("socket")
socket.Connect(IpAddress,80,5000)
'
Wait For Socket_Connected(Succesful As Boolean)
'
If Succesful Then
SetState(True)
astream.InitializePrefix(socket.InputStream,True,socket.OutputStream,"astream")
End If
'
End If
End Sub

Private Sub BtnInvia_Click
'
Dim mm As MyMessage
mm.Initialize
mm.text =EditTextSender.text
SendData(ser.ConvertObjectToBytes(mm))
'astream.Write(ser.ConvertObjectToBytes(mm))
'
End Sub

Private Sub Astream_NewData (Buffer() As Byte)
'
Dim mm As MyMessage = ser.ConvertBytesToObject(Buffer)
LblDiscussione.Text=mm.text
'
End Sub

Public Sub SendData (data() As Byte)
If isconnected Then astream.Write(data)
End Sub

Private Sub Astream_Terminated
SetState(False)
End Sub

Private Sub Astream_Error
Astream_Terminated
End Sub

Thank you for any help.
 
Upvote 0

VincenzoD

Member
Sorry @Erel , i'm learning

B4A program:

B4X:
#Region  Project Attributes
    #ApplicationLabel: B4A Example
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: False
#End Region

' B4A - Basic4Android
' Programma Android
' Utilizza la libreria Socket per comunicare con l'applicazione Visual Basic sul PC


Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Private xui As XUI
    Public socket As Socket
    Private isconnected As Boolean
    Private astream As AsyncStreams
    Private ser As B4XSerializator
    Type MyMessage (text As String)

    '
End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    '
    Private EditTextIP As EditText
    Private EditTextPORT As EditText
    Private BtnConnetti As Button
    Private LblDiscussione As Label
    Private BtnInvia As Button
    Private LbLog As Label
    Private EditTextSender As EditText
    '
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("Layout")
End Sub


Sub Activity_Resume
    ' Connessione al server
End Sub

Sub Activity_Pause (UserClosed As Boolean)
'
End Sub

Private Sub SetState (Connected As Boolean)
    isconnected=Connected
    '
    If isconnected Then
        LbLog.Text="State : Connected"
    Else
        LbLog.Text="State : Disconnected"
    End If
    '
End Sub

Private Sub BtnConnetti_Click
    Dim IpAddress As String
    'Dim Port As Int
    SetState(False)
    '
    IpAddress=EditTextIP.Text
    'Port=EditTextPORT.Text
    '
    '
    If IpAddress="" Then
        MsgboxAsync(" Destination IP cannot be empty !!! ", "")
    Else
        If astream.IsInitialized Then
            astream.Close
        End If
        '
        If socket.IsInitialized Then
            socket.Close
        End If
        '
        socket.Initialize("socket")
        socket.Connect(IpAddress,80,5000)
        '
        Wait For Socket_Connected(Succesful As Boolean)
        '
        If Succesful Then
            SetState(True)
            astream.InitializePrefix(socket.InputStream,True,socket.OutputStream,"astream")
        End If
        '
    End If
End Sub

Private Sub BtnInvia_Click
    '
    Dim mm As MyMessage
    mm.Initialize
    mm.text =EditTextSender.text
    SendData(ser.ConvertObjectToBytes(mm))
    'astream.Write(ser.ConvertObjectToBytes(mm))
    '
End Sub

Private Sub Astream_NewData (Buffer() As Byte)
    '
    Dim mm As MyMessage = ser.ConvertBytesToObject(Buffer)
    LblDiscussione.Text=mm.text
    '
End Sub

Public Sub SendData (data() As Byte)
    If isconnected Then astream.Write(data)
End Sub

Private Sub Astream_Terminated
    SetState(False)
End Sub

Private Sub Astream_Error
    Astream_Terminated
End Sub


vb.net:

B4X:
Imports System.Net
Imports System.Net.Sockets
Imports System.IO


Public Class Form1
    Private client As TcpClient
    Public STR As StreamReader
    Public STW As StreamWriter
    Public receive As String
    Public receiveAsync As String
    Public texttosend As String


    Public Sub New()

        ' Chiamata richiesta dalla finestra di progettazione.
        InitializeComponent()

        ' Aggiungere le eventuali istruzioni di inizializzazione dopo la chiamata a InitializeComponent().
        Dim localIP As IPAddress() = Dns.GetHostAddresses(Dns.GetHostName)
        For Each address As IPAddress In localIP
            If address.AddressFamily = AddressFamily.InterNetwork Then
                ServerIPTextBox.Text = address.ToString()
            End If
        Next
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        RadioButton1.Checked = True
    End Sub

    Private Sub StartButton_Click(sender As Object, e As EventArgs) Handles StartButton.Click
        If ServerIPTextBox.Text = "" Or ServerPort.Text = "" Then
            MsgBox("Attenzione! Inserire indirizzo IP o la porta !")
        Else
            Dim listener As New TcpListener(IPAddress.Any, Integer.Parse(ServerPort.Text))
            listener.Start()
            client = listener.AcceptTcpClient()
            STR = New StreamReader(client.GetStream())
            STW = New StreamWriter(client.GetStream())
            STW.AutoFlush = True
            BackgroundWorker1.RunWorkerAsync()
            BackgroundWorker2.WorkerSupportsCancellation = True
        End If


    End Sub

    Private Sub ConnectButton_Click(sender As Object, e As EventArgs) Handles ConnectButton.Click
        client = New TcpClient
        Dim IPEnd As New IPEndPoint(IPAddress.Parse(ClientIP.Text), Integer.Parse(ClientPort.Text))
        Try

            client.Connect(IPEnd)

            If (client.Connected) Then
                ChatScreenTextBox.AppendText(" Connesso al server " + Environment.NewLine)
                STR = New StreamReader(client.GetStream())
                STW = New StreamWriter(client.GetStream())
                STW.AutoFlush = True
                BackgroundWorker1.RunWorkerAsync()
                BackgroundWorker2.WorkerSupportsCancellation = True
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message.ToString)
        End Try
    End Sub

    Private Async Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        While (client.Connected)
            Try
                receive = STR.ReadLine
                receiveAsync = Await STR.ReadLineAsync
                Me.ChatScreenTextBox.Invoke(New MethodInvoker(Function()
                                                                  ChatScreenTextBox.AppendText("YOU: " + receive + Environment.NewLine)
                                                              End Function))
                receive = ""
            Catch ex As Exception
                MessageBox.Show(ex.Message.ToString)
            End Try
        End While
    End Sub

    Private Sub BackgroundWorker2_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker2.DoWork
        If (client.Connected) Then
            STW.WriteLine(texttosend)
            'STW.WriteLineAsync(texttosend)
            Me.ChatScreenTextBox.Invoke(New MethodInvoker(Function()
                                                              ChatScreenTextBox.AppendText("ME: " + texttosend + Environment.NewLine)
                                                          End Function))
        Else
            MessageBox.Show("Sending Failed")
        End If
        BackgroundWorker2.CancelAsync()

    End Sub

    Private Sub SendButton_Click(sender As Object, e As EventArgs) Handles SendButton.Click
        If (MessageTextBox.Text <> "") Then
            texttosend = MessageTextBox.Text
            BackgroundWorker2.RunWorkerAsync()
        End If
        MessageTextBox.Text = ""
    End Sub

    Private Sub RadioButton1_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton1.CheckedChanged
        GroupBox1.Enabled = True
        GroupBox2.Enabled = False
    End Sub

    Private Sub RadioButton2_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton2.CheckedChanged
        GroupBox1.Enabled = False
        GroupBox2.Enabled = True
    End Sub
End Class


I'm sorry for disturbe i just find solution to this,
From server software, i must using Vb.net
 
Upvote 0
Top