I am trying to connect to socket.io socket in R using the R function socketConnection (). However, although I can configure the socket correctly, I cannot read data from it in R.
The javascript code that I use to configure the server:
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(8005);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.on('connection', function (socket) {
setInterval(function() {
socket.emit('update', "test")
}, 1000);
});
Code for index.html:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost:8005');
socket.on('update', function (data) {
console.log(data);
});
</script>
I can check if the socket really works by going to localhost: 8005 in my web browser and opening the developer console, where I can see that the “test” is being logged. However, when I try to connect to a socket in R, follow these steps:
sock <- socketConnection("localhost", 8005, blocking = FALSE, open = "r")
readLines(sock)
Each time I run readLines (sock), I return an empty character vector. I also confirmed that I can read from other sockets in R by doing the following and getting a response from readLines (sock):
sock <- socketConnection("rstudio.com", 6789, blocking = FALSE, open = "r")
readLines(sock)
Any help would be greatly appreciated. Thanks!
(2015-09-01):
Aaron Dufour, R. javascript ,
var net = require('net');
var server = net.createServer(function(socket) {
setInterval(function() {
socket.write('Test\r\n');
socket.pipe(socket);
}, 1000)
});
server.listen(1337, '127.0.0.1');
R :
sock <- socketConnection("localhost", 1337, open = "r")
readLines(sock)
close(sock)
warning: possible EventEmitter memory leak detected. 11 end listeners added. Use emitter.setMaxListeners() to increase limit. , readLines(socket)
, close(socket) R, , : Error: This socket has been ended by the other party
, , .