今天我正在编写一个从Node.js中的服务器接收字符串的应用程序(Android)。套接字连接很好,我可以从Android发送到服务器就好了,但是当涉及从服务器接收时,readUTF()在读取时停留。以下是要发送和接收的Android代码:
Socket socket = new Socket("10.13.37.129",1337);
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
JSONObject jsonObject = new JSONObject();
jsonObject.put("data", "Tristen");
dataOutputStream.writeUTF(jsonObject.toString());
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
System.out.println("Receiving");
final byte[] buffer = {};
dataInputStream.read(buffer);
string = new String(buffer);
System.out.println("Received");
Runnable runnable1 = new Runnable() {
@Override
public void run() {
System.out.println("This is the string: " + string);
System.out.println("This is the buffer: " + buffer.length);
System.out.println("This is the buffer.ToString(): " + buffer.toString());
textView.setText(string);
}
};
runOnUiThread(runnable1);
这是发送字符串的服务器代码:
// Add a 'data' event handler to this instance of socket
clientSocket.on('data', function(data) {
console.log('DATA: ' + data);
clientSocket.write('Hello\n');
clientSocket.write('World\n');
});
有人能看出它有什么问题吗?
答案 0 :(得分:1)
readUTF()
用于读取DataOutputStream.writeUTF().
写的字符串。没有其他的。使用read(),
BufferedReader.readLine(),
等