Ich lerne Node js
mit socket
. Ich habe ein Beispielprogramm von HereSocket.io emittieren und .on funktioniert nicht
Wenn ich versuche, es auszuführen, zeigt es nicht den Fehler, aber auch nichts passiert.
Ich habe versucht und herausgefunden, dass die socket.emit
und socket.io
nicht auslösen.
Client-Seite
$("#addComment").click(function(event){
var userName = $("#name").val();
var userComment = $("#comment").text();
if(userName === "" || userComment === "") {
alert("Please fill the form.");
return;
}
socket.emit('comment_added',{user : userName, comment : userComment});
socket.on('notify_everyone',function(msg){
notifyMe(msg.user,msg.comment);
});
});
function notifyMe(user,message) {
// Let's check if the browser supports notifications
if (!("Notification" in window)) {
alert("This browser does not support desktop notification");
}
// Let's check if the user is okay to get some notification
else if (Notification.permission === "granted") {
// If it's okay let's create a notification
var options = {
body: user + "Posted a comment" + message,
dir : "ltr"
};
var notification = new Notification("Hi there",options);
}
// Otherwise, we need to ask the user for permission
// Note, Chrome does not implement the permission static property
// So we have to check for NOT 'denied' instead of 'default'
else if (Notification.permission !== 'denied') {
Notification.requestPermission(function (permission) {
// Whatever the user answers, we make sure we store the information
if (!('permission' in Notification)) {
Notification.permission = permission;
}
// If the user is okay, let's create a notification
if (permission === "granted") {
var options = {
body: user + "Posted a comment" + message,
dir : "ltr"
};
var notification = new Notification("New comment added.",options);
}
});
}
// At last, if the user already denied any notification, and you
// want to be respectful there is no need to bother them any more.
}
Server-Seite
io.on('connection',function(socket){
console.log('We have user connected !');
io.sockets.on('comment_added',function(data){
console.log(data);
db.addComment(data.user,data.comment,mysql,pool,function(error,result){
if (error) {
io.emit('error');
} else {
socket.broadcast.emit("notify_everyone",{user : data.user,comment : data.comment});
}
});
});
});