2017-01-15 39 views
-3

我想通过USB电缆将Android设备作为客户端 - 服务器网桥连接到Windows笔记本电脑。我用Java写了我的客户端代码。当我的设备连接到我的WiFi调制解调器,并且我的笔记本电脑也使用LAN电缆连接时,我将Android设备IP设置在应用程序桌面上作为连接到服务器套接字的地址。但是,当我的WiFi调制解调器关闭时,我想用USB电缆连接Android设备和笔记本电脑。我的设备的IP地址不可用,我无法连接到Android设备。将PC连接到Android设备以通过USB电缆形成客户端 - 服务器链接

另一个问题:我可以连接到服务器,并通过USB电缆打开带有IP地址的套接字。

的Android代码

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(); 
      } 
     } 
    } 
} 

我需要从服务器到客户端发送的位置数据每隔一秒;

+0

向我们展示您的努力。你尝试过什么吗?你失败了? – rupinderjeet

+0

@rupinderjeet代码added.when我使用客户端服务器之间的WIFI连接我有Android设备的IP和我写地址在一个文本文件和客户端我读取该文本文件并使用IP连接到服务器,但是当我使用USB电缆我出现错误,无法与客户端连接到服务器。 – Desert

回答

0

在客户端代码中,您正在无限地使用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帮助您摆脱循环。

+0

我需要每一秒将位置数据放在'OutPutStream'对象中。并在'InputStream'对象的客户端阅读,我改变了我的代码,但我还有问题。在通信客户​​端服务器与WIFI调制解调器在Android设备我有一个本地的IP,但是当我使用USB电缆,我没有IP我应该如何给我的客户端地址找到服务器? – Desert

0

我终于找到答案了。用于通信PC到Android设备的Client-Server表单。你应该使用ADB.you应该去巫婆cmd adb地方在您的电脑和类型> adb转发tcp:38300(端口号为例如38300)tcp:38300 和您的IDE应该关闭后使用此命令使用“localhost” Android设备IP,如this-> echoSocket = new Socket(“localhost”,38300); 并完成。

相关问题