# A chat-like program for R. library('websockets') library('RJSONIO') htmldata = 'R Chat

R Chat

R plot area

Console:

' port = 7681 w = create_server(webpage=static_text_service(htmldata), port=port) f = function(DATA,WS,...) { d = tryCatch(rawToChar(DATA),error=function(e) "") jpeg(file=itmp, width=400,height=400,quality=100) devAskNewPage(ask=FALSE) sink(file=ctmp,split=TRUE) ans = tryCatch(capture.output(eval(parse(text=d),envir=globalenv())), error = function(e) cat(as.character(e),file=ctmp)) dev.off() sink() ans = paste(ans,collapse="\n") if(file.exists(itmp)) { p = base64encode(readBin(itmp,what="raw",n=1e6)) p = paste("data:image/jpg;base64,\n",p,sep="") msg = sprintf("Client %d says: %s\n%s",WS$socket,d,ans) websocket_broadcast(toJSON(list(msg=msg, fig=p)),WS$server) } else { msg = sprintf("Client %d says: %s\n%s",WS$socket,d,ans) websocket_broadcast(toJSON(list(msg=msg)),WS$server) } } set_callback("receive",f,w) ctmp = tempfile() itmp = tempfile() cat(sprintf("Direct browsers to http://%s:%s\n",Sys.info()["nodename"],port)) while(TRUE) service(w)