简体   繁体   English

通过套接字连接Android设备和Java应用

[英]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. Android应用是运行在API 19上的模拟Nexus设备上的服务器,客户端是Java应用,它将图像发送到服务器以在其上显示。 I can't manage to connect these two. 我无法连接这两个。 I am using localhost:5001 to connect to android device and connection is being refused. 我正在使用localhost:5001连接到android设备,并且连接被拒绝。 Android app on emulator is running all the time and accepting connection on that same port. 模拟器上的Android应用始终运行,并在同一端口上接受连接。 I think port is problem but does anyone know how can i configure this properly? 我认为端口有问题,但是没有人知道我该如何正确配置它?

Java code: Java代码:

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: Android代码:

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. 如果您能够将客户端连接到同一路由器下的服务器,则意味着否则(即使用您的公共IP)存在某种阻止它的东西,可能是您的路由器。 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. 我建议在双方的连接片段中放置几行Log.d()行,看看瓶颈在哪里,或者使用一些调试工具并放置一些断点。 If you can't reach even your device, probably you're specifying an incorrect IP address. 如果连设备都无法访问,则可能是您指定了错误的IP地址。 Seeing your code, though, I see you're using 10.0.2.2 as IP. 不过,看到您的代码,我看到您正在使用10.0.2.2作为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. 请记住,这是一个localhost表示形式,并不意味着您可以将设备连接到它,这仅意味着该设备可以连接到其自身,我想您并不是在尝试实现它。 Use the internet local address instead. 请改用Internet本地地址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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