Hi,
I’m working on a project where a PC/vb.net program and an android program must be able to send information to each other(in the future with more than one android device). They don’t necessarily have to be connected all the time.
The communication must be able to be started from both devices. – So I guess that both devices have to act as both server and client ? (Or what ?)
I have with help for the forum managed to make the first way: android as server and vb.net as client.
PC->android:
Android server:
Vb.net client:
Is that an okay/smart solution – or is there at better way ?
How do the server look up the IP-address of the client ?
********* --------------------------- **********
Android -> PC.
vb.net:
Andorid:
It works for only one connection, and I cannot make a new connection before the programs I restarted.
Is it the correct/best way ? – how do I fix to work “all the time” ? (Does any one have a working example?)
If it is enough with one of the devices to act as server – then the PC/vb.net is the preferred.
Thanks in advance
Kent
I’m working on a project where a PC/vb.net program and an android program must be able to send information to each other(in the future with more than one android device). They don’t necessarily have to be connected all the time.
The communication must be able to be started from both devices. – So I guess that both devices have to act as both server and client ? (Or what ?)
I have with help for the forum managed to make the first way: android as server and vb.net as client.
PC->android:
Android server:
B4X:
Service module
Sub Process_Globals
Dim ServerSocket1 As ServerSocket
Dim Socket1 As Socket
Dim Timer1 As Timer
Dim InputStream1 As InputStream
Dim OutputStream1 As OutputStream
Dim RefreshDataFlag_1,RefreshDataFlag_2 As Boolean
Dim param_over As String
Dim MP2 As MediaPlayer
End Sub
Sub Service_Create
'If FirstTime Then
Timer1.Initialize("Timer1", 2000)
'End If
If ServerSocket1.IsInitialized = False Then
ServerSocket1.Initialize(2222, "ServerSocket1")
Log("server-socket initialiseret")
End If
End Sub
Sub Service_Start (StartingIntent As Intent)
Log("My IP: " & ServerSocket1.GetMyIP)
ServerSocket1.Listen
End Sub
Sub Service_Destroy
Timer1.Enabled = False
Socket1.Close
ServerSocket1.Close 'stop listening
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
Log("forbindet")
Else
Msgbox(LastException.Message, "Error connecting")
End If
ServerSocket1.Listen 'Continue listening to new incoming connections
End Sub
Sub Timer1_Tick
Dim BC As ByteConverter
Dim data As String
If InputStream1.BytesAvailable > 0 Then
Timer1.Enabled = False
Dim buffer(8192) As Byte
InputStream1.ReadBytes(buffer, 0, buffer.Length)
data=BC.StringFromBytes(buffer,"UTF-8")
Dim komando, param As String
Dim sep1 As Int ' index of separators
sep1 = data.IndexOf("|")
komando = data.SubString2(0, sep1)
param = data.SubString(sep1 + 1)
Log("komando: " & komando & " --- " & "param: " & param)
data_input(komando, param)
Timer1.Enabled = True
End If
End Sub
B4X:
Imports System.Net
Imports System.Net.Sockets
Public Class Form1
Dim ip As IPAddress
Dim port As Integer
Dim sock_1, sock_2, sock_3 As New TcpClient()
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
ip = IPAddress.Parse(TextBox_ip.Text)
port = TextBox_Port.Text
sock_1.Connect(ip, port)
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
sock_1.Client.Send(System.Text.Encoding.UTF8.GetBytes(TextBox1.Text))
End Sub
Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
sock_1.Close()
End Sub
Public Sub kom_terminal_1(ByVal komando As String, ByVal param As String)
If sock_1.Connected = False Then sock_1.Connect(IPAddress.Parse("192.168.0.6"), 2222)
sock_1.Client.Send(System.Text.Encoding.UTF8.GetBytes(komando & "|" & param))
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Call kom_terminal_1("21", "det er bare en test")
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
End Class
How do the server look up the IP-address of the client ?
********* --------------------------- **********
Android -> PC.
vb.net:
B4X:
Imports System.Net
Imports System.Text
Imports System.Net.Sockets
Public Class Form1
Const ipAddress As String = "127.0.0.1"
Const portNumber As Integer = 8000
Dim tcpListener As New TcpListener(portNumber)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
tcpListener.Start()
Debug.Print("Waiting for connection...")
Try 'Accept the pending client connection and return 'a TcpClient initialized for communication.
Dim tcpClient As TcpClient = tcpListener.AcceptTcpClient()
Debug.Print("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)
Debug.Print(("Modtaget: " + clientdata))
Dim responseString As String = "Tak for data(fra vb.net)"
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(responseString)
networkStream.Write(sendBytes, 0, sendBytes.Length)
Debug.Print(("Send: " + responseString)) 'Any communication with the remote client using the TcpClient can go here.
tcpClient.Close() 'Close TcpListener and TcpClient.
tcpListener.Stop()
Debug.Print("stoppet igen")
Catch ex As Exception
Debug.Print(e.ToString())
End Try
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
End Class
Andorid:
B4X:
'Activity module
Sub Process_Globals
Dim AStreams As AsyncStreams
Dim Server As ServerSocket
Dim Socket1 As Socket
Dim forbindelse As Int
End Sub
Sub Globals
Dim EditText1 As EditText
Dim lbStatus, lbResult As Label
Dim tw As TextWriter
Dim tr As TextReader
Dim sb As StringBuilder
End Sub
Sub Activity_Create(FirstTime As Boolean)
Activity.LoadLayout("1")
Socket1.Initialize("Socket1")
End Sub
'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
'AStreams.Close
Socket1.Close
End If
End Sub
Sub btnConnect_Click
Try
If Socket1.Connected=False Then Socket1.Connect("192.168.0.7" , 8000, 20000) 'Socket1.Connect("95.166.205.135" , 5100, 20000)
Catch
ChangeStatus("fail")
End Try
End Sub
Sub btnDisconnect_Click
'AStreams.Close
tr.Close
tw.Close
Socket1.Close()
ChangeStatus("disconnect")
End Sub
Sub ChangeStatus(thetype As String)
If(thetype = "connect") Then
Log("Connected to Server!")
Else If(thetype = "disconnect") Then
Log( "Disconnected")
Else If(thetype = "fail") Then
Log( "Unable to connect to Server!")
End If
End Sub
Sub Socket1_Connected (Successful As Boolean)
If Successful = False Then
Msgbox(LastException.Message, "Error connecting")
forbindelse=0
Return
End If
ChangeStatus("connect")
tr.Initialize(Socket1.InputStream)
tw.Initialize(Socket1.OutputStream)
Dim data As String
data="så kom der hul igennem - besked fra android 1"
tw.WriteLine(data)
Log("Har Send: " & data)
tw.Flush
sb.Initialize
sb.Append(tr.ReadLine)
Log("modtaget " & sb.ToString )
' Socket1.close
End Sub
Sub send_data(data As String)
tr.Initialize(Socket1.InputStream)
tw.Initialize(Socket1.OutputStream)
Dim data As String
If data="" Then data="send via send_data funk"
tw.WriteLine(data)
Log("Har sendt2: " & data)
tw.Flush
sb.Initialize
sb.Append(tr.ReadLine)
Log("modtaget2 " & sb.ToString )
End Sub
Sub Button1_Click
If Socket1.Connected=False Then Socket1.Connect("192.168.0.7" , 8000, 20000)
send_data("test")
End Sub
Is it the correct/best way ? – how do I fix to work “all the time” ? (Does any one have a working example?)
If it is enough with one of the devices to act as server – then the PC/vb.net is the preferred.
Thanks in advance
Kent
Last edited: