B4J Question B4J Example Code for Listening on Socket using Asyncstreams

Fr Simon Rundell

Member
Licensed User
Longtime User
I want to create a B4J App that listens on a given port and convert that into a keypress (to remote control an app from a B4A app which I have working at the moment to an AutoIT app, but I'd like the PC Client to use a B4x code). The latter part I think I have in hand, but I can't get my head around the implementation of Asyncstreams in B4J

Just taking the B4A Code falls over because I assume the library methods are different

This works in B4A

B4X:
Sub Initalise
    Socket1.Initialize("Socket1")
    Socket1.Connect(strServerValue , intPortValue, 20000)  
End Sub

Sub Socket1_Connected (Successful As Boolean)
   If Successful Then
        AStreams.Initialize(Socket1.InputStream, Socket1.OutputStream, "AStreams")
    Else
        ' raise error here
    End If
  
End Sub

Sub AStreams_NewData (Buffer() As Byte)
    Dim Msg As String  
    Msg = BytesToString(Buffer, 0, Buffer.Length, "UTF8")
    Log(Msg)
  
End Sub

Can anyone give me code example like this for B4J? Many thanks.
 
Last edited:

Erel

B4X founder
Staff member
Licensed User
Longtime User
Please use [code]code here...[/code] tags when posting code.

Complete non-ui program:
B4X:
Sub Process_Globals
   Private server As ServerSocket
   Private astream As AsyncStreams
End Sub

Sub AppStart (Args() As String)
   server.Initialize(51042, "server")
   server.Listen
   StartMessageLoop
End Sub

Sub server_NewConnection (Successful As Boolean, NewSocket As Socket)
   Log("New connection")
   If Successful Then
     astream.Initialize(NewSocket.InputStream, NewSocket.OutputStream, "astream")
   End If
   server.Listen
End Sub

Sub astream_NewData (Buffer() As Byte)
   Log(BytesToString(Buffer, 0, Buffer.Length, "utf8"))   
   astream.Write("received!".GetBytes("utf8"))
End Sub
 
Upvote 0
Top