我试图通过数字(从-128到127的每个数字是cpp中标准字符的范围)将png文件从我的服务器(cpp)传递到套接字(js),但是如果我使用String.fromCharCode()方法-这将不起作用
String.fromCharCode的输出与cpp上的char转换不同(对于负数),js中还有其他方法可以帮助我吗?..
客户端代码(js):
socket.onmessage = function (event) {
const splitted = event.data.split("|")
if (splitted[0] === "file -d") {
let data = splitted[2].split(",")
data = String.fromCharCode(...data)
console.log(data)
const link = document.createElement("a")
const file = new Blob([data], { type: 'application/octet-stream;charset=utf-8' })
link.href = URL.createObjectURL(file)
link.download = splitted[1]
link.click()
URL.revokeObjectURL(link.href)
} else
console.log("Received from the server: \"" + event.data + "\"")
}
字符串
服务器上的代码(cpp):
connection->send("file -d|" + "my.png" + "|" + "-119,80,78,71,13,...); // just binary data but char-->int
型
从客户端向服务器发送文件的代码(js):
submitFile.onmousedown = function () {
if (connected === true) {
let file = fileStorage.files[0]
let fileBuffer = new ArrayBuffer(0)
let fileReader = new FileReader()
fileReader.onloadend = function (event) {
fileBuffer = event.target.result
let fileData = new Int8Array(fileBuffer)
socket.send("file -u|" + file.name + "|" + "./files|" + file.size + "|" + fileData)
}
fileReader.readAsArrayBuffer(file)
} else
alert("No connection to the server")
}
型
2条答案
按热度按时间nszi6y051#
您似乎正在尝试解析
file -d
执行输出。你的输出似乎提供了格式为十进制的有符号字符类型,而不是无符号字符类型。在这种情况下,我将模拟
byte underflow
以获得负部分的(0~255)对应部分。字符串
另外,请注意,
String.fromCharCode
不接受数组作为参数。因此,应按照以下方式进行:型
所以,如果你在代码中实现这个解决方案,它看起来像这样:
型
83qze16e2#
好吧,解决办法很简单...
字符串
只是将数据转换为Int8Array,现在它工作正常。