In your server program change socket.emit
to io.sockets.emit
.
socket.emit
will send message to specific socket (client) that got connected. io.sockets.emit
will send message to all connected sockets (clients)
Question
I'm trying to create a chat system. Here it is:
The top field takes the name of the user while the bottom textarea takes the message. Once the user pressed enter the middle textarea ( which is disabled) updates itself with the new record. This is done using nodejs sockets. My problem is that if I open another instance of google chrome and I type something the other google chrome textarea does not update. I'm puzzled by this since my code should cover this case:
Here is the server.js code that handles the insertion. After it inserts it, it emits a socket with the last insertion so that the index.html can update itself.
io.sockets.on("connection",function(socket){
socket.on("send",function(data){
mongodb.connect("mongodb://127.0.0.1:27017/myDatabase",function(err,db){
if(err) throw err;
var to_be_inserted = {name: data.name,content: data.content};
db.collection("chat").insert(to_be_inserted,function(err,objects){
if(err) throw err;
var cursor = db.collection("chat").find().sort({_id: -1}).limit(1);
cursor.toArray(function(err,docs){
console.log("abc");
socket.emit("data_to_be_printed",docs);
});
});
})
})
})
As you can see once the data is inserted a socket is emitted containing the last row of the db. The index.html should handle this socket by updating itself. Here is the code that handles it:
<script>
var socket = io.connect("127.0.0.1:1337");
socket.on("data_to_be_printed",function(cursor){
var completed = document.getElementById("chatArea").value;
for(var i=0; i < cursor.length; i++)
{
console.log(cursor[i].name + " wrote: " + cursor[i].content);
var name = cursor[i].name;
var content = cursor[i].content;
var name_to_go = name.replace("/\r?\n|\r/g","");
var content_to_go = content.replace("/\r?\n|\r/g","");
completed+="\n" + name_to_go + ": " + content_to_go;
}
document.getElementById("chatArea").value = completed;
});
function keyfunction(e)
{
if((e.keyCode == 13 || e.which == 13) && !e.shiftKey)
{
socketEmitDb();
}
}
function socketEmitDb()
{
var name = document.getElementById("name").value;
var content = document.getElementById("writtenThing").value;
console.log("Name: " + name + " |||| content: " + content);
document.getElementById("name").value="";
document.getElementById("writtenThing").value="";
if(name.length > 0 && content.length > 0)
{
socket.emit("send",{"name": name,"content": content});
}else
{
alert("Make sure that the name and the message is not empty");
}
}
</script>
Should't the socket be emitted towards all opened sockets?
Solution
In your server program change socket.emit
to io.sockets.emit
.
socket.emit
will send message to specific socket (client) that got connected. io.sockets.emit
will send message to all connected sockets (clients)