0

I'm trying to do a two ways communication between a PC running .NET Client-Server and an Android device, (the code is made with Basic4Android). Sending from Android to PC works fine, the problem occours when i try to send from the PC to Android. I'm trying to use the ServerSocket but when the PC tries to connect to the Android the device, time-out is reached and an exception is raised. The code i'm using is the following:

PC .NET

 Dim sock As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
 sock.Connect(remoteip, 8565)
 Dim buffer() As Byte = UTF8.GetBytes(string)
 sock.Send(buffer)
 sock.Close()

and the Android code:

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Dim ss As ServerSocket 
    Dim IS1 As InputStream 
    Dim timerListener As Timer
End Sub


Sub Activity_Create(FirstTime As Boolean)
    timerListener.Initialize(timerListener, 1)
    ss.Initialize(8565, "ss")
    ss.Listen
End Sub

Sub ss_NewConnection (Successful As Boolean, NewSocket As Socket)
    If Successful Then
    IS1 = NewSocket.InputStream     
    timerListener.Enabled = True
    Else
    ToastMessageShow("Error.", True)
    End If
End Sub

Sub timerListener_Tick
    Dim cv As ByteConverter 
If IS1.BytesAvailable > 0 Then
    Dim buffer() As Byte
    IS1.ReadBytes(buffer, 0, IS1.BytesAvailable)
    Dim result As String = cv.StringFromBytes(buffer, "UTF8")
    ToastMessageShow(result, True)
    timerListener.Enabled = False
End If
End Sub

What can be the issue? Thank you in advance!!

user2959923
  • 144
  • 1
  • 2
  • 14

3 Answers3

0

You should use AsyncStreams to read the data.

In your PC read a byte from the stream after you write the message. This will cause the thread to wait for the byte to be available instead of closing the socket before the device read the message.

Erel
  • 1,802
  • 2
  • 15
  • 58
0

In Sub timerListener_Tick(), control the timer action:

timerListener.Enabled = False
...
timerListener.Enabled = True

Timer will receive the messages periodly.

tomexou
  • 343
  • 2
  • 5
0

Closing the PC socket straight after sending will cause you a send error because it's closing when you are in fact still sending, better to use a global variable to hold the socket instance, but if you want to send synchronous (wait for the transfer to commit) use the example from MSDN.

Synchronous Client Socket Example

I wouldn't recommend it though, personally, I would prefer to use async transfers, like one of the above post recommends. See->Asynchronous Client Socket Example