All:
I am new to node.js and socket.io, and have no idea about how the protocol works. But I am learning.
I got a beginner question about socket.io,if I got code from some tutorial like:
var http = require('http');
var fs = require('fs');
var app = http.createServer(
function(request, response){
console.log("New Connection!");
fs.readFile(
"client.html","utf-8",
function(err, data){
response.writeHead(200, {'Content-Type':'text/html'});
response.write(data);
response.end();
}
);
}
).listen(1337);
var io = require('socket.io').listen(app);
io.sockets.on(
'connection',
function( socket ){
socket.on(
'message_to_server',
function(data){
io.sockets.emit('message_to_client',{message: data['message']});
}
);
}
);
My question is can someone tells me how this code works? What I am confused is:
It seems like the socket.io just wraps the app,sending and receiving event message and doing callback. But I wonder why those action will not triger app's request event, I put console.log("New Connection!"); inside that callback, and it only displays when I input the server address and press enter in browser, but when I press the send button, it will not display anything?
Here is my client code:
<!DOCTYPE html>
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
// Out client code here.
var socketio = io.connect("192.168.1.150:1337");
socketio.on(
'message_to_client',
function(data){
document.getElementById("chatlog")
.innerHTML=
("<hr/>"+data['message']+document.getElementById("chatlog").innerHTML);
}
);
function sendMessage(){
var msg = document.getElementById("message_input").value;
if(msg!=""){
socketio.emit("message_to_server", {message:msg});
}
}
</script>
</head>
<body>
<input type="text" id="message_input" />
<button onclick="sendMessage()">SEND</button>
<div id="chatlog"></div>
</body>
</html>