有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

安卓如何在Java中从DataInputStream获取字符串?

我正在开发一个由socket组成的应用程序。它需要将一个字符串值从客户端(安卓设备)传输到服务器(运行Ubuntu的PC)。 在服务器端代码中,我需要将通过socket传输的值存储在字符串变量中

下面是我用来将字符串值发送到服务器的代码

//instantiating the socket object for the client
Socket client = new Socket("192.168.0.103", port);

OutputStream outToServer = client.getOutputStream();

DataOutputStream out = new DataOutputStream(outToServer);

String msg = "My String Value";

//Message to be send to server
out.writeUTF(msg);

//Closing the client's socket. No connections after this.
client.close();  

下面是我用来在服务器上获取字符串值的代码

//Server object. Stores the reference to the socket object returned by the accept()
//The returned socket object contains established connection to the client.
Socket server = serverSocket.accept();

DataInputStream in = new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
//This prints "My String Message"

//Something like this i want to do.
String msg = in.readUTF();

//closing the server socket. No connection now.
server.close();

现在发生的事情是服务器端的程序被卡在了线路上:

String msg = in.readUTF();

将DataInputStream中的字符串值存储到字符串变量中的正确方法是什么


共 (2) 个答案

  1. # 1 楼答案

    正如@david conrad所解释的,当您第一次读取时,输入缓冲区在下一次读取时变为空,因此解决方案仍然是首先将内容缓冲到字符串中,然后您可以将该字符串用于任何内容(例如println)

    DataInputStream in = new DataInputStream(server.getInputStream());
    String msg = in.readUTF();
    System.out.println(msg);
    
  2. # 2 楼答案

    您只写一次数据,而在另一端您尝试读取两次,但只有一个数据副本需要读取

    DataInputStream in = new DataInputStream(server.getInputStream());
    System.out.println(in.readUTF());
    //This prints "My String Message"
    

    这还将使用流中存在的字符串的唯一副本

    Right now what is happening is the program at server side is getting stuck at line:

    String msg = in.readUTF();
    

    当您第二次调用in.readUTF()时,它会等待客户端发送更多数据(另一个字符串),但由于客户端从不发送更多数据,它将永远等待(或者直到您终止它,或者连接超时)