0

I am trying to get my server made on vb.net to send messages to my client made on android. I have a client and server made on vb.net, I can send and receive messages (text) between them without problem. But when I try to make the client work the same on Android, I can not receive messages to the client (android), but if I could get it to send a message to the server (vb.net) .. They are stuck with this, and I do not understand how to continue

SERVER VB.NET



Imports System.Net.Sockets
Imports System.Text

Public Class Servidor
    Dim Tcp As TcpListener
    Dim th As New Threading.Thread(AddressOf Rutina)
    Dim ejecuto = False
    Private Sub Servidor_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        CheckForIllegalCrossThreadCalls = False
    End Sub
    Dim tcpservercliente As New TcpClient
    Public Function Rutina()
        Try
            Do
                If ejecuto = True Then
                    Exit Do
                End If
                If Tcp.Pending = True Then
                    tcpservercliente.Client = Tcp.AcceptSocket
                End If
                If tcpservercliente.Available > 0 Then
                    Dim databytes(1000) As Byte
                    Dim decode As New ASCIIEncoding
                    tcpservercliente.Client.Receive(databytes)
                    txtRecibido.Text += vbCrLf & "Cliente Android: " & decode.GetString(databytes)
                End If

            Loop
        Catch ex As System.InvalidOperationException
            MsgBox("Error: " & ex.Message)
        End Try




    End Function
    Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
        Try
            Tcp = New TcpListener(System.Net.IPAddress.Parse("192.168.1.8"), 1371)
            Tcp.Start()
            th.Start()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End Sub

    Private Sub Servidor_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
        th.Abort("Rutina")
        Application.Exit()
    End Sub

    Private Sub btnEnviar_Click(sender As Object, e As EventArgs) Handles btnEnviar.Click
        Try
            Dim decode As New ASCIIEncoding
            tcpservercliente.Client.Send(decode.GetBytes(txtMensajeEnviar.Text))
        Catch ex As System.Net.Sockets.SocketException
            MsgBox(ex.Message)
        End Try

    End Sub


CLIENT ANDROID


//CLASS RM 

public class RM extends AsyncTask<Void, Void, Void> {
    Socket socket;
    BufferedReader input;

    @Override
    protected Void doInBackground(Void... voids) {
        try {
            socket = new Socket("192.168.1.8",1371);
            InputStreamReader streamReader = new InputStreamReader(socket.getInputStream());
            input = new BufferedReader(streamReader);
            if(input.ready()){
                Log.i("AsyncTask", "Ready ");
            }else{
                Log.i("AsyncTask", "No Ready");
            }
            input.close();
            socket.close();
        }catch (IOException e){
            e.printStackTrace();
        }

        return null;
    }
}



//VOID MAIN ACTIVITY

RM mr = new RM();
        mr.execute();

The times I've tried to see that it returns, it's always empty. The message that is being sent from the server is not arriving

Sorry my bad english

==========================================

EDIT: This is the class I use to send messages from the client (android) to the server (vb.net)

package com.example.app_test_client;

import android.os.AsyncTask;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
public class MessageSender extends AsyncTask<String, Void, Void> {

    Socket socket;
    PrintWriter pw;
    @Override
    protected Void doInBackground(String... voids) {
        String mensaje_enviar = voids[0];
        try {
            socket = new Socket("192.168.1.8",1371);
            pw = new PrintWriter(socket.getOutputStream());
            pw.write(mensaje_enviar);
            pw.flush();
            pw.close();
            socket.close();
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }
}

CODE MAIN ACTIVITY (CLIENT ANDROID)

package com.example.app_test_client;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity{
    EditText mensaje_enviar;
    TextView mensaje_recibido;


    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mensaje_enviar = (EditText)findViewById(R.id.txtTexto);
        mensaje_recibido = (TextView)findViewById(R.id.lblMensaje);
    }

    public void enviar(View v){
        MessageSender MensajeRemitente = new MessageSender();
        MensajeRemitente.execute(mensaje_enviar.getText().toString());
    }
}

The void "enviar" I have it in the "onClick" button. All this to send messages from the client (android) to the server (vb.net) works for me.

Based on this class "MessageSender", I made another equal to receive messages on the client (android) but it has not worked

luisbriyan
  • 95
  • 9

1 Answers1

1

If you are trying to receive the message in the Android device, then you are missing reading the message itself with String messageReceived = input.readLine();. Your code would look like this:

...
socket = new Socket("192.168.1.8",1371);
InputStreamReader streamReader = new InputStreamReader(socket.getInputStream());
input = new BufferedReader(streamReader);
String messageReceived = input.readLine();
...

You will have the message sent from the server in messageReceived.

EDIT

Without getting into much details, when you read the data sent from the server, you need to know when the data sent "ends", and the easiest way you have with your current implementation is to print a "line end" (a vbCrLf character in VB) when you send the message. Thus, in your Sub btnEnviar_Click you need to add a vbCrLf as follows:

tcpservercliente.Client.Send(decode.GetBytes(txtMensajeEnviar.Text & vbCrLf))

Additional notes

  1. When data is being read from the server the socket needs to know when the data ends. There are several ways of achieving this, but the easiest way is in your case is to read "a line ending" with String messageReceived = br.readLine();. If the server doesn't send any "line end" (as in your current implementation), it will keep waiting for it and hence it appears that the programs hungs. That is what is happening in your case when you note that you cannot do anything else after reading the message - it is just waiting for something that will never come.
  2. It is not necessary that you check input.ready() when reading from the server. This will only be true when the data has been completely sent from the server, and there is a great chance that the data is still being sent when it is invoked.
  3. If you want to know better how TCP sockets works, this SO question has good examples that you can try.
Heraldo
  • 407
  • 2
  • 11
  • It does not return any value to me, it seems more that some error occurs when arriving at the line "input.readLine ()". Since I put a "log" to see if it arrives well to that line: "socket = new Socket("192.168.1.8",1371); InputStreamReader streamReader = new InputStreamReader(socket.getInputStream()); Log.i("Tst", "1"); input = new BufferedReader(streamReader); Log.i("Tst", "2"); messageReceived = input.readLine(); Log.i("Tst", "3"); input.close(); socket.close();" but never reaches "3". The program no longer allows me to send messages after executing that code. https://i.imgur.com/WUz7uB5.png – luisbriyan Jun 02 '19 at 16:36
  • I see. 1) When you say "The program no longer allows me to send messages after executing that code", you refer to sending messages from the server using `btnEnviar_Click`? 2) Do you have the possibility to modify the server code? – Heraldo Jun 02 '19 at 20:05
  • 1. I mean that in the client (android) I can send message to the server (vb.net) without problems, but if I run the code to read messages from the client (android) the app no longer works (it does not close or anything that) and after that he does not let me send messages (as if the problem of receiving a message when executing, will affect the whole app). 2. Yes I can modify the server – luisbriyan Jun 02 '19 at 21:43
  • I will explain again in case I do not explain myself correctly. I have a client made on vb.net where I can send and receive messages from my server on vb.net (the one I posted above). I made a client on android where I can send messages to the server, but I can not receive messages from the server (vb.net). The problem is that some code fails to receive the message (android) .. For example, I can send several messages from my client (android) to the server (vb.net) without problem, but if I execute the code to receive messages in the client (previously sending a message from my server) – luisbriyan Jun 02 '19 at 22:01
  • ..Then a failure occurs (it does not show any error or anything) and affects the whole program, causing it now to not be able to send messages from the client (android) .. This makes me think that when executing the code there is something wrong , and that totally affects the program. I do not know what it could be. I have seen several tutorials and guides, and they always use the same way. Will my execution of the "doInBackground" be wrong? Thank you – luisbriyan Jun 02 '19 at 22:03
  • I will add more details in my answer. In the meantime, do you have any other code that works with sockets? In other words, are there other methods like `doInBackground` in your Android client? I ask this because the code from `doInBackground` only reads from the server, and you are implying that you want also to send data to the server, which is not possible from the code you have published. – Heraldo Jun 03 '19 at 00:25
  • I have added more information in my question. Adding the class I use to send messages from the client (android) to the server (vb.net) that works well, and I used that by modifying to try to receive messages, but without success – luisbriyan Jun 03 '19 at 01:47
  • I have tried adding "vbCrLf" in the code to send from the server, but I still can not receive the message in the client (android). This is my class to receive message https://i.imgur.com/IGf4VC2.png. When executing the code in the client to receive message, it never reaches the line to receive the message. I did a test by adding "Log" and it only comes up before "readLine" https://i.imgur.com/EL70YQf.png is executed – luisbriyan Jun 03 '19 at 21:21
  • The client is waiting for me to receive a message because it no longer allows me to send messages to the server, and if I stop the server then it generates an error https://i.imgur.com/ZjuvX9X.png showing that the client was waiting for the message that never arrives – luisbriyan Jun 03 '19 at 21:21
  • I've tried with while in the read.line, and many more changes, but nothing .. Is there any chance that you can try the server and client on your pc? Maybe I can see the solution better. I do not know what else to try – luisbriyan Jun 04 '19 at 04:01
  • Ok, the answers I provided are based under the assumption that the server was working fine, but now I have my doubts about it, as there are a few miss use patterns in your implementation. I have tested your code with a few modifications and I got it working. If you like, I can share my version of it. – Heraldo Jun 04 '19 at 11:39
  • Yes please, it would be very helpful – luisbriyan Jun 04 '19 at 13:46
  • Here you go: https://github.com/heraldovalenti/sockets-with-vb-and-java – Heraldo Jun 04 '19 at 16:51
  • Thank you very much, you help me understand more. It works for me to send a message from the vb.net server to the android client. Although I must send it 2 times so that it arrives in the client, but it is a slight detail. Again thank you very much – luisbriyan Jun 04 '19 at 20:07
  • Hey, I'm glad to hear that. Keep up with the learning :) Good luck! – Heraldo Jun 05 '19 at 10:56