简体   繁体   中英

Connecting Android device and Java app over socket

Android app is server on emulated Nexus device running on API 19, and client is Java app which is sending image to server to be displayed on it. I can't manage to connect these two. I am using localhost:5001 to connect to android device and connection is being refused. Android app on emulator is running all the time and accepting connection on that same port. I think port is problem but does anyone know how can i configure this properly?

Java code:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

public class Server {
    public static final int PORT = 5001;
    public static final String IP_ADDRESS = "localhost";// "10.0.2.2";
    public static Socket ss;
    public static final String FILE = "slika.jpg";

    public static void main(String[] args) throws InterruptedException {
        boolean finished = false;
        while (!finished) {
            try {
                System.out.println("Waiting...");
                ss = new Socket(IP_ADDRESS, PORT);
                System.out.println("Connected!");
                OutputStream out = ss.getOutputStream();
                File file = new File(FILE);
                System.out.println("File size: " + file.length());
                finished = true;
                byte[] b = new byte[(int) file.length()];
                out.write((int)file.length());
                try {
                    FileInputStream fileInputStream = new FileInputStream(file);
                    fileInputStream.read(b);
                } catch (FileNotFoundException e) {
                    System.out.println("File Not Found.");
                    e.printStackTrace();
                } catch (IOException e1) {
                    System.out.println("Error Reading The File.");
                    e1.printStackTrace();
                }
                out.write(b);
                out.flush();
                System.out.println("Finished sending!");
            } catch (Exception e) {
                Thread.sleep(1000);
            } finally {
                if (ss != null)
                    try {
                        ss.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
            }

        }
    }
}

Android code:

package com.example.filereceiver;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

import android.os.Bundle;
import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.Menu;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity {

    public static final int PORT = 5001;
    TextView informator;
    ImageView image;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        informator = (TextView) findViewById(R.id.informator);
        image = (ImageView) findViewById(R.id.image);
        informator.setText("Waiting!");
        Log.i("DEBUGGER","Waiting!");

        new Thread() {

            @Override
            public void run() {
                ServerSocket listener = null;
                Log.i("DEBUGGER","Waiting for connection");
                try {
                    listener = new ServerSocket(PORT);
                    Socket sock = listener.accept();
                    Log.i("DEBUGGER","Connected");
                    InputStream in = sock.getInputStream();
                    int size = in.read();
                    byte[] b = new byte[size];
                    in.read(b);
                    Bitmap myBitmap = BitmapFactory.decodeByteArray(b, 0, size);
                    image.setImageBitmap(myBitmap);
                    MainActivity.this.runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            MainActivity.this.informator
                                    .setText("TRANSFER COMPLETE!");
                            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                                    MainActivity.this)
                                    .setSmallIcon(R.drawable.ic_launcher) 
                                    .setContentTitle("Info") 
                                    .setContentText("Transfer complete!") 
                                    .setAutoCancel(true); 
                            Intent intent = new Intent(MainActivity.this,
                                    MainActivity.class);
                            PendingIntent pi = PendingIntent.getActivity(
                                    MainActivity.this, 0, intent,
                                    Intent.FLAG_ACTIVITY_NEW_TASK);
                            mBuilder.setContentIntent(pi);
                            NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                            mNotificationManager.notify(0, mBuilder.build());
                        }

                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }finally{
                    if(listener!=null)try {
                        listener.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }.start();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

You don't specify if you're running both devices (server and client) under the same LAN, in which case you can discard connectivity problems. If not, this might be a test, though. If you're able to connect your client to your server under the same router, that means that otherwise (ie, using your public IPs) there's something blocking it, probably your router. Another issues could be antiviruses, OS ports blocking, router ports blocking...

If you're not able to connect both either under the same router connection, definitely it's a code issue. I'd suggest put several Log.d() lines in the connectivity snippets on both sides and see where the bottleneck is, or use some debugging tool and put some breakpoints. If you can't reach even your device, probably you're specifying an incorrect IP address. Seeing your code, though, I see you're using 10.0.2.2 as IP. Keep in mind this is a localhost representation and doesn't mean you'd be able to connect devices to it, this just means that this device can connect to itself, and I think you're not trying to achieve that. Use the internet local address instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM