4

i tried to make an application that send data from android to computer (java to vb.net). The data sending is working in eclipse java project, but not in android project . But i have a problem. no incoming data to visual basic in my computer. VB Code :

 Imports System.Net.Sockets
 Imports System.Threading
 Imports System.IO

Public Class Form1

Dim Listener As New TcpListener(65535)
Dim Client As New TcpClient
Dim Message As String = ""

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim ListThread As New Thread(New ThreadStart(AddressOf Listening))
    ListThread.Start()
End Sub

Private Sub Listening()
    Listener.Start()
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    Client = New TcpClient("192.168.100.3", 65535)

    Dim Writer As New StreamWriter(Client.GetStream())
    Writer.Write(TextBox2.Text)
    Writer.Flush()
End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    If Listener.Pending = True Then
        Message = ""
        Client = Listener.AcceptTcpClient()

        Dim Reader As New StreamReader(Client.GetStream())
        While Reader.Peek > -1
            Message = Message + Convert.ToChar(Reader.Read()).ToString
        End While

        MsgBox(Message, MsgBoxStyle.OkOnly)
    End If
 End Sub

Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As     System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    Listener.Stop()
End Sub

End Class

java code :

package com.example.androidclient2;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {
TextView serverMessage;
Thread m_objThreadClient;
Socket clientSocket;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    serverMessage=(TextView)findViewById(R.id.textView1);
}
public void Start(View view)
{
m_objThreadClient=new Thread(new Runnable() {
      public void run()
       {
          try 
           {
             clientSocket= new Socket("192.168.100.3",65535);
             ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream());
             oos.writeObject("Hellow there");
             Message serverMessage= Message.obtain();
             ObjectInputStream ois =new     ObjectInputStream(clientSocket.getInputStream());
             String strMessage = (String)ois.readObject();
            serverMessage.obj=strMessage;
            mHandler.sendMessage(serverMessage); 
            oos.close();
            ois.close();
           } 
           catch (Exception e) 
           {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

         }
        });

 m_objThreadClient.start();

}
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
    messageDisplay(msg.obj.toString());
}
};
public void messageDisplay(String servermessage)
{
serverMessage.setText(""+servermessage);
}

}

And Thanks For The help .

fares
  • 55
  • 1
  • 1
  • 8
  • is your android device and your computer on the same local network(that is 192.168.100.x)? Also, please don't use port 65535 – Cruncher Nov 21 '13 at 20:40
  • yes , it is . and why not port 65535 ? which one to choose ? – fares Nov 21 '13 at 20:42
  • Just because it's the last port number, there's probably a better chance of a port conflict. Picking something in the private port range 49152 through 65535 is good, I would just stay clear of the first and last 10 in these ranges. Pick something rather arbitrary somewhere in the middle – Cruncher Nov 21 '13 at 20:48
  • You could also use the registered port ranges, and pick something that is unassigned. http://stackoverflow.com/questions/133879/how-should-one-go-about-choosing-a-default-tcp-ip-port-for-a-new-service – Cruncher Nov 21 '13 at 20:49
  • aha ... i got it , i though it's better to get the last number . but what is the problem here ? thanks . – fares Nov 21 '13 at 20:52

1 Answers1

7

Have just created and tested this class on android today:

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

public class TcpClient {

private static final String TAG = TcpClient.class.getSimpleName();

private Socket socket;
private PrintWriter out;
private boolean connected;

public TcpClient()
{
    socket = null;
    out = null;
    connected = false;
}


public void connect(Context context, String host, int port)
{
    new ConnectTask(context).execute(host, String.valueOf(port));
}

private class ConnectTask extends AsyncTask<String, Void, Void> {

    private Context context;

    public ConnectTask(Context context) {
        this.context = context;
    }

    @Override
    protected void onPreExecute() {
        showToast(context, "Connecting..");
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(Void result) {
        if (connected) {
            showToast(context, "Connection successfull");
        }           
        super.onPostExecute(result);
    }

    private String host;
    private int port;

    @Override
    protected Void doInBackground(String... params) {
        try {
            String host = params[0];
            int port = Integer.parseInt(params[1]);
            socket = new Socket(host, port);
            out = new PrintWriter(socket.getOutputStream(), true);
        } catch (UnknownHostException e) {
            showToast(context, "Don't know about host: " + host + ":" + port);
            Log.e(TAG, e.getMessage());
        } catch (IOException e) {
            showToast(context, "Couldn't get I/O for the connection to: " + host + ":" + port);
            Log.e(TAG, e.getMessage());
        }
        connected = true;
        return null;
    }


}

public void disconnect(Context context)
{
    if ( connected )
    {
        try {
            out.close();
            socket.close();
            connected = false;
        } catch (IOException e) {
            showToast(context, "Couldn't get I/O for the connection");
            Log.e(TAG, e.getMessage());
        }            
    }
}


/**
 * Send command to a Pure Data audio engine. 
 */
public void send(String command)
{
    if ( connected ) out.println(command +";");   
}

private void showToast(final Context context, final String message) {
    new Handler(context.getMainLooper()).post(new Runnable() {

        @Override
        public void run() {
            Toast.makeText(context, message, Toast.LENGTH_LONG).show();
        }
    });
}
}

It might help you even though I see no obvious error in your code.

Is the device on the same WiFi network as your computer? It won't work via USB for instance.

cYrixmorten
  • 7,110
  • 3
  • 25
  • 33
  • It does not have errors. Are you sure you have imported the correct packages? I'll add the imports to the code. – cYrixmorten Nov 21 '13 at 21:32
  • Well, this works. But why sending twice? I have a C# application running to check the number of connected application, and every time I load the activity, it says "A new application connected" and saying twice. – ssi-anik Sep 12 '15 at 01:37
  • As @fares said that there were error, that's true, if you are not connected to the remote host just because of some exception, you're showing that I'm connected? Changed the connection status based on error or success. – ssi-anik Sep 12 '15 at 08:45