Skip to content

Instantly share code, notes, and snippets.

@hagino3000
Created December 8, 2011 18:42
Show Gist options
  • Save hagino3000/1447986 to your computer and use it in GitHub Desktop.
Save hagino3000/1447986 to your computer and use it in GitHub Desktop.
WebSocket with binary data
var socket = null;
function bootstrap() {
// 適当な図形を描画
var c = document.getElementById('mycanvas');
var ctx = c.getContext('2d');
ctx.globalalpha = 0.3;
for(var i=0; i<1000; i++) {
ctx.beginPath();
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
ctx.strokeStyle = 'rgb(' + r + ',' + g + ',' + b + ')';
ctx.moveTo(Math.random()*200, Math.random()*200);
ctx.lineTo(Math.random()*200, Math.random()*200);
ctx.stroke();
}
// Socketの初期化
socket = new WebSocket('ws://localhost:8082');
socket.binaryType = 'arraybuffer';
socket.onopen = function() {
send(ctx);
}
socket.onmessage = handleReceive;
};
function send(ctx) {
// RAWデータをそのまま送信
var data = ctx.getImageData(0, 0, 200, 200).data;
var byteArray = new Uint8Array(data);
socket.send(byteArray.buffer);
}
function handleReceive(message) {
// 受信したRAWデータをcanvasに
var c = resultCanvas = document.getElementById('result');
var ctx = c.getContext('2d');
var imageData = ctx.createImageData(200, 200);
var pixels = imageData.data;
var buffer = new Uint8Array(message.data);
for (var i=0; i < pixels.length; i++) {
pixels[i] = buffer[i];
}
ctx.putImageData(imageData, 0, 0);
}
<html>
<head>
<script src="./client.js"></script>
</head>
<body onload="bootstrap()">
<div style="width:210px;float:left;">
Input<br>
<canvas id="mycanvas" width="200" height="200"></canvas>
</div>
<div style="float:left;width:210px;">
Result<br>
<canvas id="result" width="200" height="200"></canvas>
</div>
</body>
</html>
#!/usr/bin/env node
var WebSocketServer = require('websocket').server,
http = require('http'),
fs = require('fs');
var server = http.createServer(function(request, response) {
var filePath;
if (request.url == '/') {
filePath = './index.html';
} else {
filePath = './client.js';
}
var data = fs.readFileSync(filePath, 'utf8');
console.log((new Date()) + " Received request for " + request.url);
response.end(data);
});
server.listen(8082, function() {
console.log((new Date()) + " Server is listening on port 8082");
});
wsServer = new WebSocketServer({
httpServer: server,
// デフォルトでは65535byte以上受けつけないので
// 値を増やしてみる
maxReceivedFrameSize: 0x1000000,
autoAcceptConnections: false
});
wsServer.on('request', function(request) {
var connection = request.accept(null, request.origin);
console.log((new Date()) + " Connection accepted.");
connection.on('message', function(message) {
if (message.type === 'utf8') {
// NOP
}
else if (message.type === 'binary') {
// バイナリデータを受信した場合
console.log("Received Binary Message of " + message.binaryData.length + " bytes");
console.log(message.binaryData);
var data = message.binaryData;
var len = data.length;
// 受信したRAW画像をグレースケールにする
var buf = new Buffer(len);
var arr = new Uint32Array(buf);
for (var i = 0; i < len; i+=4 ) {
var r = data.readUInt8(i);
var g = data.readUInt8(i+1);
var b = data.readUInt8(i+2);
var y = Math.floor((77*r + 28*g + 151*b)/255);
// Canvasにそのまま投入するために
// 4チャンネル8ビットのRGBAにする
var v = y + (y << 8) + (y << 16) + (0xFF << 24);
buf.writeInt32LE(v, i);
}
// グレースケールにした物をクライアントに送信する
connection.sendBytes(buf);
}
});
connection.on('close', function(reasonCode, description) {
console.log((new Date()) + " Peer " + connection.remoteAddress + " disconnected.");
});
});
@rico345100
Copy link

Awesome :)

@msyfls123
Copy link

It’s really useful to me, thx!

@birgersp
Copy link

Very useful comments
(sarcasm)

@DeathBot9
Copy link

Even years later, still an excellent bit of code to help understand some concepts quickly. Thank you!

@JimsC
Copy link

JimsC commented Jan 11, 2019

非常感谢,非常有用

@Dystorian
Copy link

nike ta seur

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment