[英]Sending and receiving Bytes over Android socket two issues:
I've got an issue with JAVA/ Android studio surrounding sending and receiving bytes.我遇到了 JAVA/Android 工作室围绕发送和接收字节的问题。 Notably: sending and receiving byte values over 127 using TCP sockets.
值得注意的是:使用 TCP sockets 发送和接收超过 127 的字节值。
I receive data here:我在这里收到数据:
try {
mBufferOut = new PrintWriter(socket.getOutputStream());
mBufferIn = new InputStreamReader(socket.getInputStream(), "UTF-8");
char[] buffer = new char[64];
while (mRun) {
mBufferIn.read(buffer);
mServerMessage = String.valueOf(buffer);
if (mServerMessage != null && mMessageListener != null) {
mMessageListener.messageReceived(mServerMessage);
}
mServerMessage = null;
}
and send data here:并在此处发送数据:
public void sendMessage(final char[] message) {
Runnable runnable = new Runnable() {
@Override
public void run() {
if (mBufferOut != null) {
mBufferOut.write(message);
mBufferOut.flush();
}
}
};
Thread thread = new Thread(runnable);
thread.start();
}
When I receive data, all data over 127 in values is returned as "231, 191, 189".当我收到数据时,所有超过 127 的数据都返回为“231、191、189”。 When I send data, every byte with a value x over 127 is returned as "195, x".
当我发送数据时,值 x 超过 127 的每个字节都返回为“195,x”。
How can I cleanly solve this issue?我怎样才能干净地解决这个问题?
I don't think that sending a String
as array of char
, and using String.valueOf()
to restore it is the right way.我不认为将
String
作为char
数组发送,并使用String.valueOf()
来恢复它是正确的方法。
String
already has a mechanism to convert itself to/from bytes: String
已经有一种将自身转换为字节的机制:
byte[] bytes = text.getBytes("UTF-8");
...
String text = new String(bytes, "UTF-8");
Try using this 2 methods to convert String
to byte[]
and vice versa.尝试使用这 2 种方法将
String
转换为byte[]
,反之亦然。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.