简体   繁体   中英

Connect PC to Android device to form a Client-Server link via USB cable

I want to connect Android device with a Windows laptop as a client-server bridge via USB cable. I wrote my client code with Java. When my device is connected to my WiFi modem and my laptop connected too with LAN cable, I set android device IP on application desktop as address for connecting to server socket. But, when my WiFi modem is off and I want to connect Android device and laptop with USB cable. My device's IP address is unavailable and I can't connect to Android device.

Another question: Can I connect to server and open socket with IP address through USB cable.

Android Code

public class ActivityMain extends AppCompatActivity {
private Button button ;
public static final int TIMEOUT = 10;
private String connectionStatus = null;
private Handler mHandler = null;
private ServerSocket serverSocket = null;
private Socket socket = null;
private ObjectOutputStream  objectOutputStream;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);

configure_button();
 }

  @Override
  public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
      case 10:
        configure_button();
        break;
      default:
        break;
    }
  }
  void configure_button() {
    // first check for permissions
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
      ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
      ActivityCompat.checkSelfPermission(this, Manifest.permission.INTERNET)               != PackageManager.PERMISSION_GRANTED) {

      if  (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)  {
        requestPermissions(new String[] {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.INTERNET}, 10);
      }
      return;
    }
    //this code won't execute if permissions are not allower, because in the line above there is return statement.
    button.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        //initialize serverSocket socket in a new separate thread
        new Thread(initializeConnection).start();
        String msg = "Attempting to connect";
        Toast.makeText(ActivityMain.this, msg, Toast.LENGTH_SHORT).show();
      }
    });
  }

  //threads
  private final Runnable initializeConnection = new Thread(){
@Override
public void run() {
  // initialize server socket
  try {
    serverSocket = new ServerSocket(38300);
    serverSocket.setSoTimeout(ActivityMain.TIMEOUT * 1000);

    //attempt to accept a connection
    socket = serverSocket.accept();

    objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
    try {
      while(true) {
        for (int i = 0; i < 1000; i++) {
          //objectOutputStream.reset();
          objectOutputStream.writeObject("number" + i);
          // objectOutputStream.writeBytes("number"+i);
          System.out.println("send>" + "number" + i);
        }
      }
    } catch (IOException ioException) {
      //Log.e(ActivityMain.TAG, "" + ioException);
    }
  } catch (SocketTimeoutException e) {
    connectionStatus = "Connection has timed objectOutputStream! Please try again";
    // mHandler.post(showConnectionStatus);
  }
  catch(IOException e)
  {
    //Log.e(ActivityMain.TAG, ""+e);
  }

  if(socket != null)
  {
    connectionStatus = "Connection was succesful";
    // mHandler.post(showConnectionStatus);
  }
}
};
}

Client Code

public class CCC {  
    public static void main(String[] args)
    {
        System.out.println("hi");
        Socket echoSocket = null;
        ObjectOutputStream out = null;
        ObjectInputStream in = null;
        String message = "";

        // Create socket connection with host address as localhost and port number with 38300 
        try
        {
            echoSocket = new Socket("192.168.1.19", 38300);

            in = new ObjectInputStream(echoSocket.getInputStream());

            // Communicating with the server
            try
            {
                while(true){
                message = (String) in.readObject();
                System.out.println("server>" + message);

                }
            }
            catch (ClassNotFoundException classNot)
            {
                System.err.println("data received in unknown format");
            }
        }
        catch (UnknownHostException e)
        {
            System.err.println("Don't know about host: LocalHost.");
            System.exit(1);
        }
        catch (IOException e)
        {
            System.err.println("Couldn't get I/O for " + "the connection to: LocalHost:");
            System.exit(1);
        }
        finally
        {
            // Closing connection
            try
            {
                in.close();

                if (echoSocket != null)
                {
                    echoSocket.close();
                }
            }
            catch (IOException ioException)
            {
                ioException.printStackTrace();
            }
        }
    }
}

i need send location data from server to client every one second;

I find answer finally. for communication PC to Android device Client-Server form. you should use ADB.you should go witch cmd to adb place in your pc and type>adb forward tcp:38300(port number for example 38300) tcp:38300 and your IDE should be closed after use this command use "localhost" instead Android device IP like this->echoSocket = new Socket("localhost", 38300); and is done.

In Client code, You are reading ObjectInputStream infinitely using while(true) . You are not breaking out of loop if you reach the end of file.

The program can't read any more, because it has reached the end of the file, so the EOFException might be thrown. Use if(in.readObject() != null) for checking this. You should catch the exception and handle it naturally.

try {
    while(true) {
        message = in.readObject(); 
        System.out.println("server>" + message);
    }
} catch (EOFException e) { 
    // handle exception
    System.out.println("Reached end of file while reading.");
}

EOFException helps you breaks out of the loop.

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