Android Question Write to socket is slow [Solved]

darabon

Active Member
Hi
I try to write data to a socket with below codes
B4X:
Sub so_Connected (Successful As Boolean)
    If Successful Then
      Dim s2 As AsyncStreams
      s2.Initialize(so.InputStream,so.OutputStream,"so")
      Dim s() As Byte
      s = Command.GetBytes("UTF8")
      s2.Write(s)
    End If
End Sub
But here is a problem
When I write to the socket, it takes 3 seconds to write to the socket
But response is very speedily
Also, I try to use below parameters but not working
B4X:
Private Sub SetBufferSize(Sock As Socket, Size As Int)
    Dim r As Reflector
    r.Target = Sock
    Dim native_socket As Object
    native_socket = r.GetField("socket")
    r.Target = native_socket
    r.RunMethod2("setSendBufferSize", Size, "java.lang.int")
    r.RunMethod2("setReceiveBufferSize", Size, "java.lang.int")
    Try
    r.RunMethod2("setTcpNoDelay", True, "java.lang.boolean")
    Catch
    End Try
End Sub
 

Erel

Administrator
Staff member
Licensed User
I did a test using that example.

B4X:
Sub btnSend_Click
    SendData (ser.ConvertObjectToBytes(DateTime.Now))
End Sub

Sub AStream_NewData (Buffer() As Byte)
    If xui.IsB4J Then
        SendData(Buffer)
    Else
        Dim t As Long = ser.ConvertBytesToObject(Buffer)
        Log(DateTime.Now - t)
    End If
End Sub
The time that it took the message to be sent from the Android device to the PC and back to the Android device is around 30 milliseconds.
The 3 seconds delay comes from somewhere else. It is not related to flushing.
 
Upvote 0

darabon

Active Member
I did a test using that example.

B4X:
Sub btnSend_Click
    SendData (ser.ConvertObjectToBytes(DateTime.Now))
End Sub

Sub AStream_NewData (Buffer() As Byte)
    If xui.IsB4J Then
        SendData(Buffer)
    Else
        Dim t As Long = ser.ConvertBytesToObject(Buffer)
        Log(DateTime.Now - t)
    End If
End Sub
The time that it took the message to be sent from the Android device to the PC and back to the Android device is around 30 milliseconds.
The 3 seconds delay comes from somewhere else. It is not related to flushing.
Thank you
Maybe Wifi server is a problem
I'm confused
When I use other socket tools for test wifi server, it is a good working
But in my app is slow
Actually I don't have any idea for solving it
 
Upvote 0

darabon

Active Member
I think the problem is Wifi server
But when I use other socket tools in mobile and test with wifi server, speed is good
 
Upvote 0

darabon

Active Member
The problem solved successfully guys
It's necessary use \r\n end of string according to below code
B4X:
Dim b() As Byte
            b = Command.GetBytes("UTF8")
            Dim s(b.Length + 2) As Byte
            
            For i = 0 To b.Length - 1
                s(i) = b(i)   
            Next
            
            s(b.Length) = 10
            s(b.Length + 1) = 13

Actually we have to add \r\n code directory to array not "\r\n"
 
Upvote 0
Top