Last active
October 27, 2023 16:32
-
-
Save shigeki/5334078 to your computer and use it in GitHub Desktop.
標準入力をWebSocketで送信するサンプルプログラム
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require('http'); | |
var WebSocketServer = require('websocket').server; | |
var port = 8080; | |
process.stdin.resume(); | |
process.stdin.setEncoding('utf8'); | |
var index = '<!DOCTYPE html><html><head><title>stdin-to-ws</title></head>' | |
+ '<body><div id="msg"></div><script>' | |
+ 'var msg = document.getElementById("msg");' | |
+ 'var ws = new WebSocket("ws:localhost:8080/stdin-to-ws", "stdin-to-ws");' | |
+ 'ws.onmessage = function(e) {' | |
+ ' var data = document.createElement("div");' | |
+ ' data.innerHTML = e.data;' | |
+ ' msg.appendChild(data);' | |
+ '};' | |
+ '</script></body></html>'; | |
var server = http.createServer(function(req, res) { | |
if (req.url === '/') { | |
res.writeHead(200, {'content-type': 'text/html', | |
'content-length': Buffer.byteLength(index)}); | |
res.end(index); | |
} else { | |
res.writeHead(404); | |
res.end(); | |
} | |
}); | |
server.listen(port, function() { | |
console.log('Listening on ' + port); | |
}); | |
var wsServer = new WebSocketServer({ | |
httpServer: server, | |
autoAcceptConnections: false | |
}); | |
wsServer.on('request', function(req) { | |
var conn = req.accept('stdin-to-ws', req.origin); | |
console.log((new Date()) + ' Peer ' + conn.remoteAddress + ' connected.'); | |
process.stdin.on('data', function(chunk) { | |
conn.sendUTF('stdin: ' + chunk); | |
}); | |
process.stdin.on('end', function() { | |
conn.sendUTF('stdin end'); | |
}); | |
conn.on('close', function(reasonCode, description) { | |
console.log((new Date()) + ' Peer ' + conn.remoteAddress + ' disconnected.'); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment