samp-cef 解决客户端显示服务端传回数据乱码问题
核心思路:
在服务端传递之前把中文数据转换为十六进制,再把这个十六进制传给客户端,客户端收到以后再把十六进制转换为gbk
服务端代码示例:
// StringToHex
stock StringToHex(const string[], dest[], size = sizeof(dest)) {
new hexChars[] = "0123456789ABCDEF";
new len = strlen(string);
new j = 0;
for (new i = 0; i < len && (j < size - 3); i++) {
new c = string[i] & 0xFF;
dest[j++] = hexChars[c >>> 4];
dest[j++] = hexChars[c & 0x0F];
}
dest[j] = 0;
}
// 调用方式
stock Notify(playerid, const type[], const title[], const message[], time)
{
new hTitle[256], hMsg[512];
StringToHex(title, hTitle);
StringToHex(message, hMsg);
cef_emit_event(playerid, "send:action:notificar",
CEFSTR(type),
CEFSTR(hTitle),
CEFSTR(hMsg),
CEFINT(time)
);
return 1;
}
客户端代码示例
/**
* 将 Hex 字符串转换为 GBK 编码的中文
*/
function hexToGbkString(hex) {
if (!hex) return "";
// 1. 将 Hex 每两个字符转为一个字节数字
const bytes = new Uint8Array(hex.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
// 2. 使用 TextDecoder 以 gbk 编码解码字节流
// 注意:如果你的服务器是繁体,请把 'gbk' 换成 'big5'
const decoder = new TextDecoder('gbk');
return decoder.decode(bytes);
}
cef.on("send:action:notificar", (type, title, message, time) => {
// 解码 GBK 编码的字符串
title = hexToGbkString(title);
message = hexToGbkString(message);
Alert(type, title, message, time);
});

浙公网安备 33010602011771号