gpt4 book ai didi

java - 从带有波斯字符的数据接收字节数组

转载 作者:行者123 更新时间:2023-12-01 12:41:55 26 4
gpt4 key购买 nike

我的代码是一个信使,通过 WiFi 将消息从 Android 设备发送到另一个 Android 设备。

这是我的代码,在此类中我发送消息:

public class ClientThread extends Thread {

String address;
String message;
int portNum;
InetAddress serverAddr;
Socket socket;
PrintWriter out;
boolean broadcast;

public ClientThread(String addr, int port, String msg, boolean bcast) throws IOException {
address = addr;
portNum = port;
message = msg;
broadcast = bcast;
}

public void run() {
try {

ChatService.portsocket.setBroadcast(broadcast);
// Charset.forName("UTF-8").encode(message);
// Log.d("client",new String(message.getBytes()));
// byte[] b = EncodingUtils.getBytes(message,
// Charset.forName("UTF-8").name());
DatagramPacket packet1 = new DatagramPacket(message.getBytes(), message.length(),
InetAddress.getByName(address), 5555);
ChatService.portsocket.send(packet1);

}
catch (Exception e) {
e.printStackTrace();
}
}
}

在这个类上我收到消息:

public class ChatService extends Service {

public static String serverIP;
public static int serverPort = 5555;
private ServerSocket serverSocket;
private serverThread sThread;
public static final String BROADCAST_ACTION = "UpdateEvent";
public static DatagramSocket portsocket;
Intent intent;
int i = 0;

@Override
public IBinder onBind(Intent arg0) {
return null;
}

private class serverThread extends Thread {

public void run() {
try {
serverIP = getLocalIpAddress();
Log.v("addr", serverIP);
if (serverIP != null) {
serverSocket = new ServerSocket(serverPort);
Log.v("socket", "created");
while (true) {
/*
* Socket client = serverSocket.accept();
* Log.v("client", "received");
*/
try {
byte [] buf = new byte [1024];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
ChatService.portsocket.receive(packet);
byte [] result = new byte [packet.getLength()];
System.arraycopy(packet.getData(), 0, result, 0, packet.getLength());

String msg = new String(result);

Log.d("armin", msg);
updateGui(msg, packet.getAddress());

}
catch (Exception e) {
}
}
}
}
catch (Exception e) {
}
}
}
}

当我输入“例如”并发送它时,应用程序收到的消息是一个不连贯的单词,例如“有人有解决办法吗?

最佳答案

如果你有

String message = ...;

这被转换为字节[]

byte[] bytes = message.getBytes();

那么 DatagramPacket 必须使用构建

new DatagramPacket(bytes, bytes.length(), ... );

您的通话使用

new DatagramPacket( message.getBytes, message.length(),..,

但这使用字符串长度,但波斯语每个字符需要多个字节。

字符串 Ë 包含 5 个字符,但 UTF-8 编码需要 10 个字节。您需要发送 10 个字节。

关于java - 从带有波斯字符的数据接收字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25023788/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com