I was writinig a game using Socket.io and I have problem, when server create new img (new character) i can only see it on one computer..
I wanna in this case, for every connected computer see the same amount of images
Better if you look on this
Thanks for every help
SERVER:
var handler = function(req, res) {
fs.readFile('./index.html', function (err, data) {
if(err) throw err;
res.writeHead(200);
res.end(data);
});
}
var app = require('http').createServer(handler);
var io = require('socket.io').listen(app);
var fs = require('fs');
var port = 3250;
app.listen(port);
var postacie = [];
var ile=0;
// socket.io
io.sockets.on('connection', function (socket) {
postacie[ile]=createChar();
ile++;
io.sockets.emit("tworz", postacie);
socket.on("disconnect", function()
{
postacie.splice(0, 1);
io.sockets.emit("tworz", postacie);
})
});
function createChar()
{
var postac = {
src: "http://img703.imageshack.us/img703/1416/2st.gif",
id: "character"
}
return postac;
}
CLIENT:
<!DOCTYPE html>
<html>
<head>
<title>Real tie game</title>
<script src="socket.io/socket.io.js"></script>
<script type="text/javascript">
window.onload = function() {
var socket = io.connect('http://localhost:3250');
socket.on("tworz", function(data)
{
for (var i=0; i < data.length; i++) {
var element = document.createElement('img');
element.src = data[i].src;
element.id = data[i].id;
var body = document.getElementsByTagName('body')
body.appendChild(element);
};
})
}
</script>
</head>
<body>
</body>
</html>
AND IT LOOK LIKE THIS
http://img42.imageshack.us/img42/4793/q10w.jpg
I refactored your code a bit. Hope it helps you move in correct direction:
The main idea is to use 3 basic messages:
join -- when new client connects the server send info about newbie to all other clients;
list -- when new client connects the server send him the list of already connected clients;
leave -- when someone disconnected the server send id of disconnected client
Server:
var handler = function(req, res) {
fs.readFile('./index.html', function (err, data) {
if(err) throw err;
res.writeHead(200);
res.end(data);
});
}
var app = require('http').createServer(handler);
var io = require('socket.io').listen(app);
var fs = require('fs');
var port = 3250;
app.listen(port);
var postacie = [];
var idGenerator = 0;
// socket.io
io.sockets.on('connection', function (socket) {
var pId = idGenerator++;
socket.emit("list", postacie);
var postac = createChar(pId);
postacie.push(postac);
io.sockets.emit("join", postac);
socket.on("disconnect", function()
{
var sId = "character" + pId;
for (var i = 0,n=postacie.length; i < n; ++i) {
var postac = postacie[i];
if (postac.id == sId) {
io.sockets.emit("leave", {id:postac.id});
postacie.splice(i, 1);
break;
}
}
});
});
function createChar(id)
{
var postac = {
src: "http://img703.imageshack.us/img703/1416/2st.gif",
id: "character" + id
};
return postac;
}
Client:
<!DOCTYPE html>
<html>
<head>
<title>Real tie game</title>
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
window.onload = function() {
var socket = io.connect('http://localhost:3250');
socket.on("join", function(data)
{
var element = document.createElement('img');
element.src = data.src;
element.id = data.id;
var body = document.getElementsByTagName('body')[0];
body.appendChild(element);
});
socket.on("list", function(data)
{
for (var i=0; i < data.length; i++) {
var element = document.createElement('img');
element.src = data[i].src;
element.id = data[i].id;
var body = document.getElementsByTagName('body')[0];
body.appendChild(element);
};
});
socket.on("leave", function(data)
{
var element = document.getElementById(data.id);
if (element)
element.parentNode.removeChild(element);
});
}
</script>
</head>
<body>
</body>
</html>
Related
i have code to make pdf and succeeded in downloading and opening it, but i want to send pdf to my server on node js, and i have made app.post on server but i can't make pdf become base64 and save it on server
in frontend
<script type="text/javascript">
function genPDF() {
html2canvas(document.getElementById('testDiv')).then(function (canvas) {
var img = canvas.toDataURL('image/png');
var doc = new jsPDF('landscape');
doc.addImage(img, 'png', 10, 10);
var temp = doc.save('test.pdf');
var post = new XMLHttpRequest();
post.open("POST", "/receive");
post.send(temp);
}
</script>
Download PDF
in server
app.post('/receive', function (request, respond) {
var body = '';
var filePath = './static' + '/document/Document.pdf';
//
request.on('data', function (data) {
body += data;
});
request.on('end', function () {
var data = body.replace(/^data:image\/\w+;base64,/, "");
var buf = new Buffer(data, 'base64');
fs.writeFile(filePath, buf, function (err) {
if (err) throw err
respond.end();
});
});
});
how to send var temp = doc.save('test.pdf'); server and generate pdf to base64?
Use the below code this will help you.
IN FE
<script type = "text/javascript">
function genPDF() {
html2canvas(document.getElementById('testDiv')).then(function (canvas) {
var img = canvas.toDataURL('image/png');
var doc = new jsPDF('landscape');
doc.addImage(img, 'png', 10, 10);
var temp = doc.save('test.pdf');
var data = new FormData();
data.append("pdf_file", temp);
var post = new XMLHttpRequest();
post.open("POST", "/receive");
post.send(data);
}
</script>
<a href = "javascript:genPDF()" > Download PDF </a>
IN BE
const fs = require('fs');
const multipartMiddleware = require('connect-multiparty')();
const express = require('express');
const app = express();
const port = 8000;
const filePath = './static' + '/document/Document.pdf';
app.post('/', multipartMiddleware, (request, response) => {
fs.readFile(request.files.pdf_file.path, (err, data) => {
fs.writeFile(filePath, data, function (err) {
if (err) throw err;
response.send('Done')
});
})
})
app.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
});
When using the cmd to run the node server.js and launch the localhost:3434 in the web browser I am getting the error:
in Chrome:
Connection closed before receiving a handshake response.
in firefox:
Firefox can't establish a connection to the server at ws://localhost:3434/
Could you pls help
server.js
var http = require('http'),
fs = require('fs');
fs.readFile('../index.html', function (err, html) {
if (err) {
throw err;
}
http.createServer(function (request, response) {
response.writeHeader(200, { "Content-Type": "text/html" });
response.write(html);
response.end();
}).listen(3434);
});
index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!--<script type="text/javascript" src="../../js/adapter.js"></script>-->
<!--<script type="text/javascript" src="../../js/webrtc.js"></script>-->
<title>Simple WebRTC video chat</title>
</head>
<body>
<header>
<video id="localVideo" autoplay="autoplay" muted="muted" style="width:40%;"></video>
<video id="remoteVideo" autoplay="autoplay" style="width:40%;"></video>
<input type="button" id="start" onclick="start(true)" value="Start Video"; />
</header>
<script>
var RTCPeerConnection = null;
var getUserMedia = null;
var attachMediaStream = null;
var reattachMediaStream = null;
var webrtcDetectedBrowser = null;
var webrtcDetectedVersion = null;
function trace(text) {
// This function is used for logging.
if (text[text.length - 1] == '\n') {
text = text.substring(0, text.length - 1);
}
console.log((performance.now() / 1000).toFixed(3) + ": " + text);
}
if (navigator.mozGetUserMedia) {
console.log("This appears to be Firefox");
webrtcDetectedBrowser = "firefox";
webrtcDetectedVersion =
parseInt(navigator.userAgent.match(/Firefox\/([0- 9]+)\./)[1]);
// The RTCPeerConnection object.
RTCPeerConnection = mozRTCPeerConnection;
// The RTCSessionDescription object.
RTCSessionDescription = mozRTCSessionDescription;
// The RTCIceCandidate object.
RTCIceCandidate = mozRTCIceCandidate;
// Get UserMedia (only difference is the prefix).
getUserMedia = navigator.mozGetUserMedia.bind(navigator);
// Creates iceServer from the url for FF.
createIceServer = function (url, username, password) {
var iceServer = null;
var url_parts = url.split(':');
if (url_parts[0].indexOf('stun') === 0) {
// Create iceServer with stun url.
iceServer = { 'url': url };
} else if (url_parts[0].indexOf('turn') === 0 &&
(url.indexOf('transport=udp') !== -1 ||
url.indexOf('?transport') === -1)) {
// Create iceServer with turn url.
// Ignore the transport parameter from TURN url.
var turn_url_parts = url.split("?");
iceServer = {
'url': turn_url_parts[0],
'credential': password,
'username': username
};
}
return iceServer;
};
// Attach a media stream to an element.
attachMediaStream = function (element, stream) {
console.log("Attaching media stream");
element.mozSrcObject = stream;
element.play();
};
reattachMediaStream = function (to, from) {
console.log("Reattaching media stream");
to.mozSrcObject = from.mozSrcObject;
to.play();
};
MediaStream.prototype.getVideoTracks = function () {
return [];
};
MediaStream.prototype.getAudioTracks = function () {
return [];
};
} else if (navigator.webkitGetUserMedia) {
console.log("This appears to be Chrome");
webrtcDetectedBrowser = "chrome";
webrtcDetectedVersion =
parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2]);
// Creates iceServer from the url for Chrome.
createIceServer = function (url, username, password) {
var iceServer = null;
var url_parts = url.split(':');
if (url_parts[0].indexOf('stun') === 0) {
// Create iceServer with stun url.
iceServer = { 'url': url };
} else if (url_parts[0].indexOf('turn') === 0) {
if (webrtcDetectedVersion < 28) {
var url_turn_parts = url.split("turn:");
iceServer = {
'url': 'turn:' + username + '#' + url_turn_parts[1],
'credential': password
};
} else {
iceServer = {
'url': url,
'credential': password,
'username': username
};
}
}
return iceServer;
};
// The RTCPeerConnection object.
RTCPeerConnection = webkitRTCPeerConnection;
// Get UserMedia (only difference is the prefix).
// Code from Adam Barth.
getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
// Attach a media stream to an element.
attachMediaStream = function (element, stream) {
if (typeof element.srcObject !== 'undefined') {
element.srcObject = stream;
} else if (typeof element.mozSrcObject !== 'undefined') {
element.mozSrcObject = stream;
} else if (typeof element.src !== 'undefined') {
element.src = URL.createObjectURL(stream);
} else {
console.log('Error attaching stream to element.');
}
};
reattachMediaStream = function (to, from) {
to.src = from.src;
};
// The representation of tracks in a stream is changed in M26.
// Unify them for earlier Chrome versions in the coexisting period.
if (!webkitMediaStream.prototype.getVideoTracks) {
webkitMediaStream.prototype.getVideoTracks = function () {
return this.videoTracks;
};
webkitMediaStream.prototype.getAudioTracks = function () {
return this.audioTracks;
};
}
if (!webkitRTCPeerConnection.prototype.getLocalStreams) {
webkitRTCPeerConnection.prototype.getLocalStreams = function () {
return this.localStreams;
};
webkitRTCPeerConnection.prototype.getRemoteStreams = function () {
return this.remoteStreams;
};
}
} else {
console.log("Browser does not appear to be WebRTC-capable");
}
var localVideo;
var remoteVideo;
var peerConnection;
var localStream;
var optional = { optional: [{ DtlsSrtpKeyAgreement: true }] }
var peerConnectionConfig = { 'iceServers': [{ 'url': 'stun:stun.services.mozilla.com' }, { 'url': 'stun:stun.l.google.com:19302' }] };
navigator.getUserMedia = navigator.getUserMedia || navigator.mozGetUserMedia || navigator.webkitGetUserMedia;
window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
window.RTCIceCandidate = window.RTCIceCandidate || window.mozRTCIceCandidate || window.webkitRTCIceCandidate;
window.RTCSessionDescription = window.RTCSessionDescription || window.mozRTCSessionDescription || window.webkitRTCSessionDescription;
localVideo = document.getElementById("localVideo");
remoteVideo = document.getElementById("remoteVideo");
serverConnection = new WebSocket('ws://localhost:3434');
serverConnection.onmessage = gotMessageFromServer;
var constraints = {
video: true,
audio: true,
};
if (navigator.getUserMedia) {
navigator.getUserMedia(constraints, getUserMediaSuccess, getUserMediaError);
} else {
alert('Your browser does not support getUserMedia API');
}
function getUserMediaSuccess(stream) {
localStream = stream;
localVideo.src = window.URL.createObjectURL(stream);
}
function start(isCaller) {
peerConnection = new RTCPeerConnection(peerConnectionConfig, optional);
peerConnection.onicecandidate = gotIceCandidate;
peerConnection.onaddstream = gotRemoteStream;
peerConnection.addStream(localStream);
if (isCaller) {
peerConnection.createOffer(gotDescription, createOfferError);
}
}
function gotMessageFromServer(message) {
if (!peerConnection) start(false);
var signal = JSON.parse(message.data);
if (signal.sdp) {
peerConnection.setRemoteDescription(new RTCSessionDescription(signal.sdp), function () {
peerConnection.createAnswer(gotDescription, createAnswerError);
});
} else if (signal.ice) {
peerConnection.addIceCandidate(new RTCIceCandidate(signal.ice));
}
}
function gotIceCandidate(event) {
if (event.candidate != null) {
serverConnection.send(JSON.stringify({ 'ice': event.candidate }));
}
}
function gotDescription(description) {
console.log('got description');
peerConnection.setLocalDescription(description, function () {
serverConnection.send(JSON.stringify({ 'sdp': description }));
}, function () { console.log('set description error') });
}
function gotRemoteStream(event) {
console.log("got remote stream");
remoteVideo.src = window.URL.createObjectURL(event.stream);
}
// Error functions....
function getUserMediaError(error) {
console.log(error);
}
function createOfferError(error) {
console.log(error);
}
function createAnswerError(error) {
console.log(error);
}
</script>
</body>
</html>
In order to handle websocket connections your http-server should handle 'upgrade'-event (see here - https://nodejs.org/api/http.html#http_event_upgrade_1)
For example, here is the working example (it uses ws-module):
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({noServer: true});
var http = require('http'),
fs = require('fs');
fs.readFile('../index.html', function (err, html) {
if (err) {
throw err;
}
var server = http.createServer(function (request, response) {
response.writeHeader(200, { "Content-Type": "text/html" });
response.write(html);
response.end();
})
server.listen(3434);
server.on('upgrade', wss.handleUpgrade);
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('something');
});
});
Here are docs for ws - https://github.com/websockets/ws
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Editor</title>
<style type="text/css" media="screen">
body {
overflow: hidden;
}
#editor {
margin: 0;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
</style>
</head>
<body>
<script src="http://127.0.0.1:8080/socket.io/socket.io.js"> </script>
<script>
(function(){
var getNode = function(s){
return document.querySelector(s);
},
textarea = getNode('.code editor');
try{
var socket = io.connect('http://127.0.0.1:8080');
} catch(e){
}
if(socket !== undefined){
//put latest string in DB to ACE
socket.on('output', function(data){
if(data.length){
var x = data.length-1;
editor.setValue(data[x].code);
}
});
socket.on('code-changes', function(){
editor.on("change", function(data){
var code = editor.getValue();
code = data;
socket.emit('input',{
code: data
});
});
});
/*
// after keydown put new string to DB
editor.on('change', function(data){
var code = editor.getValue();
socket.emit('input',{
code: code
});
});
//if(asciiValue <=0 || asciiValue >= 255){
socket.emit('input',{
code: code
});
console.log("inserted");
*/
}
})();
</script>
<div id="aceEditor" style="height: 500px; width: 500px">some text</div>
<script src="src-noconflict/ace.js" type="text/javascript" charset="utf-8"> </script>
<script>
var editor = ace.edit("aceEditor");
var code = editor.getValue();
//editor.setValue("new code here");
editor.getSession().setValue(editor.getValue(), 1);
editor.setTheme("ace/theme/twilight");
editor.session.setMode("ace/mode/javascript");
</script>
</body>
</html>
Server.js:
var mongo = require('mongodb').MongoClient;
var app = require('express')();
var http = require('http').Server(app);
var client = require('socket.io')(http);//.listen(8080).sockets;
app.get('/', function(req, res){
res.sendFile(__dirname + '/static' + '/index.html');
});
mongo.connect('mongodb://127.0.0.1/code', function(err, db){
if(err) throw err;
client.on('connection', function(socket){
var col = db.collection('messages');
col.find().limit(3).sort({_id: 1}).toArray(function(err, res){
if(err) throw err;
socket.emit('output',res);
});
socket.on('input', function(data){
var code = data.code;
client.emit('output', [data]);
console.log(data);
col.insert({code: code}, function(){
console.log("inserted");
})
});
});
});
http.listen(8080, function(){
console.log('listening on 8080');
});
I having problems sending code from ace editor to mongodb via a socket.emit.
and I'm not why the code is not sending to mongo. I tried to emit the code with editor.getValue(); I'm not sure 100% how editor.on(change) works fully..... Any tips would be much appreciated.
I think you are doing wrong here:
//socket.on('code-changes', function(){ // Editor's changes should not be within socket event handling
editor.on("change", function(data){
var code = editor.getValue();
code = data;
socket.emit('input',{
code: data
});
});
//});
Basically,
I first initiate socket.io like this:
var io = require('socket.io')(1337);
Then, after using http to get a POST request and check some info, I try this:
var updateArray = {timer:"start"};
jsonUpdate = JSON.stringify(updateArray);
io.emit('update', jsonUpdate);
But it doesn't send the sockets, and I really can't understand the socket.io documentation sadly, so I'd be happy if someone can help me out.
Server code:
var http = require('http');
var fs = require('fs');
var io = require('socket.io')(1337);
var initialBomb = 0;
function now() {
return Math.floor(new Date() / 1000);
}
http.createServer(function (req, res) {
var body = "";
req.on('data', function (chunk) {
if (req.method == 'POST') {
body += chunk;
}
});
req.on('end', function () {
parsedBody = JSON.parse(body);
if (parsedBody.round["bomb"] == "planted") {
var rightNow = now();
var initialCheck = initialBomb + 41;
if (rightNow > initialCheck) {
initialBomb = now();
var updateArray = {timer:"start"};
jsonUpdate = JSON.stringify(updateArray);
io.emit('update', jsonUpdate);
console.log(jsonUpdate);
}
}
});
}).listen(3000);
Client Code:
<script>
var socket = io('87.98.219.48:1337');
socket.on('update', function(payload) {
var data = JSON.parse(payload);
console.log(payload);
if (data['timer'] == 'start') {
initTick = timerNow();
setTimeout(tick, delay);
}
});
</script>
I have the following code:
var room = "1";
var chat = io.connect("localhost:3700/");
self.chat = chat;
chat.on("connection", function(socket){
socket.emit("room", room);
socket.on('message', function (data) {
self.receiveMessage(data);
});
});
chat.broadcast.to(room).emit('send',"HEllo");
receiveMessage:
receiveMessage: function(data){
var $elem = $("#chat1");
var $content = $elem.find(".messageText");
if(data.message) {
messages.push(data);
var html = '';
for(var i=0; i<messages.length; i++) {
html += '<b>' + (messages[i].username ? messages[i].username : 'Server') + ': </b>';
html += messages[i].message + '<br />';
}
$content.html(html);
} else {
console.log("There is a problem:", data);
}
}
The line chat.broadcast.to(room).emit('send',"HEllo"); gives me the error:
Uncaught TypeError: Cannot call method 'to' of undefined
What am I doing wrong?
Not really sure but I think you can send a broadcast only on connection.
You can try this:
var room = "1";
var chat = io.connect("localhost:3700/");
self.chat = chat;
chat.on("connection", function(socket){
socket.emit("room", room);
socket.on('message', function (data) {
self.receiveMessage(data);
});
chat.broadcast.to(room).emit('send',"HEllo");
});
Of course you can also send the broadcast in a separate handler, i.e.:
var room = "1";
var chat = io.connect("localhost:3700/");
self.chat = chat;
chat.on("connection", function(socket){
socket.emit("room", room);
socket.on('message', function (data) {
self.receiveMessage(data);
});
socket.on('foo event', function(data) {
chat.broadcast.to(room).emit('send',"HEllo");
}
});