프로그래밍/Js

websocket 바이너리 전송 arraybuffer

소행성왕자 2022. 5. 6. 15:24

웹소켓 전송시  response ByteBuffer 로 받을때에

결과

JS

let SOCKET_URL = "wss://~~~";
let socket = new WebSocket(SOCKET_URL);
socket.binaryType = "arraybuffer"; // 바이너리로 받을려면 해야함
socket.onopen = function(e) {
socket.send("---> socket send");
}
socket.onmessage = function(event) {
if(typeof event.data == "string") console.log("string 메세지");
else {
console.log("스트링타입아님");
console.log(event.data.byteLength);
console.log(event.data); // ArrayBuffer 출력
let bytearray = new Uint8Array(event.data);
let str = String.fromCharCode.apply(null, bytearray);
console.log(str); // 서버에서 euc-kr 받아오니 화면에서 한글 깨짐
let str2 = new TextDecoder("euc-kr").decode(bytearray);
console.log(str2); // euc-kr 변환되어 한글 정상적으로 나옴
for(let i=0; i<bytearray.length; i++) {
console.log(bytearray[i];
}
}
}
socket.onclose = function(event) {
}
socket.onerror = function(error) {
}

 

JAVA

....
byte[] = res = inputData.send3();
ByteBuffer buf = ByteBuffer.wrap(res);
// sync
//userSession.getBasicRemote().sendBinary(buf);
// async
userSession.getAsyncRemote().sendBinary(buf, new SendHandler() {
@Override
public void onResult(SendResult result) {
System.out.println(" [All] userSession.getId():"+userSession.getId()+"전송상태:"+result.isOK());
}
});
for(byte b : (byte[]) res) {
System.out.println(String.format("%02x ", b));
}