1
0

More than 3 years have passed since last update.

Base64でエンコードされたバイナリデータをデコードしてバイナリデータとして別サーバーに中継する方法

Last updated at Posted at 2021-08-13

概要

node.jsを使ってWebsocketクライアントから流れてきた、Base64形式のバイナリデータをバイナリ形式に直して別のサーバーに中継する実装をやった時のメモ

構成

クライアント → 中継サーバー(今回の実装) → 解析サーバー

実装

node.js
var WebSocketServer = require('websocket').server;
var WebSocketClient = require('websocket').client;
var http = require('http');

var clientConnection;
var wsserver = http.createServer(handleRequest);

var server = new WebSocketServer({
  httpServer: wsserver,
  autoAcceptConnections: true,
});

client.connect('ws://localhost:8000','echo-protocol');
client.on('connect', function (connection) {
   clientConnection = connection;
});

server.on('connect', function(connection) {
  connection.on('message', function(data){
    const buff = Buffer.from(data.payload, 'base64');

       // データを加工する場合、以下実装を行う。加工が必要なかったら↑のbuffをそのまま中継する
    var outData = new Uint8Array(buff.length + 1);
    outData[0] = 0x70; // 追加する文字 ※必要があれば
    for (var i = 0; i < buff.length; i++) {
      outData[1 + i] = buff[i];
    }

    if (clientConnection) {
      clientConnection.send(Buffer.from(outData));
    }
  })
});

wsserver.listen('8080', function(){
  console.log("Server listening on: http://localhost:%s", HTTP_SERVER_PORT);
});
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0