简体   繁体   English

通过USB线将PC连接到Android设备以形成Client-Server链接

[英]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.我想通过 USB 电缆将 Android 设备与 Windows 笔记本电脑连接为客户端 - 服务器桥接器。 I wrote my client code with Java.我用 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.当我的设备连接到我的 WiFi 调制解调器并且我的笔记本电脑也通过 LAN 电缆连接时,我将应用程序桌面上的 android 设备 IP 设置为连接到服务器套接字的地址。 But, when my WiFi modem is off and I want to connect Android device and laptop with USB cable.但是,当我的 WiFi 调制解调器关闭时,我想用 USB 线连接 Android 设备和笔记本电脑。 My device's IP address is unavailable and I can't connect to Android device.我的设备的 IP 地址不可用,我无法连接到 Android 设备。

Another question: Can I connect to server and open socket with IP address through USB cable.另一个问题:我可以通过USB线连接到服务器并打开带有IP地址的套接字吗?

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.用于通信 PC 到 Android 设备的 Client-Server 形式。 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);您应该使用 ADB。您应该使用 cmd 将 adb 放置在您的电脑中并键入> adb forward tcp:38300(port number for example 38300) tcp:38300 并且您的 IDE 应该在使用此命令后关闭,请使用“localhost”而不是 Android像这样的设备 IP->echoSocket = new Socket("localhost", 38300); and is done.并完成。

In Client code, You are reading ObjectInputStream infinitely using while(true) .在客户端代码中,您正在使用while(true)无限读取 ObjectInputStream 。 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.程序不能再读了,因为它已经到了文件的末尾,所以可能会抛出EOFException Use if(in.readObject() != null) for checking this.使用if(in.readObject() != null)进行检查。 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. EOFException帮助您跳出循环。

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

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