[英]Communicate Android Device to Localhost (My Windows 8 PC) over / via USB Cable
[英]Connect PC to Android device to form a Client-Server link via USB cable
我想通過 USB 電纜將 Android 設備與 Windows 筆記本電腦連接為客戶端 - 服務器橋接器。 我用 Java 編寫了我的客戶端代碼。 當我的設備連接到我的 WiFi 調制解調器並且我的筆記本電腦也通過 LAN 電纜連接時,我將應用程序桌面上的 android 設備 IP 設置為連接到服務器套接字的地址。 但是,當我的 WiFi 調制解調器關閉時,我想用 USB 線連接 Android 設備和筆記本電腦。 我的設備的 IP 地址不可用,我無法連接到 Android 設備。
另一個問題:我可以通過USB線連接到服務器並打開帶有IP地址的套接字嗎?
安卓代碼
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);
}
}
};
}
客戶代碼
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();
}
}
}
}
我需要每隔一秒從服務器向客戶端發送位置數據;
我終於找到了答案。 用於通信 PC 到 Android 設備的 Client-Server 形式。 您應該使用 ADB。您應該使用 cmd 將 adb 放置在您的電腦中並鍵入> adb forward tcp:38300(port number for example 38300) tcp:38300 並且您的 IDE 應該在使用此命令后關閉,請使用“localhost”而不是 Android像這樣的設備 IP->echoSocket = new Socket("localhost", 38300); 並完成。
在客戶端代碼中,您正在使用while(true)
無限讀取 ObjectInputStream 。 如果到達文件末尾,則不會跳出循環。
程序不能再讀了,因為它已經到了文件的末尾,所以可能會拋出EOFException
。 使用if(in.readObject() != null)
進行檢查。 您應該捕獲異常並自然地處理它。
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
幫助您跳出循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.