Making a Socket Connection
4:02:28 - 4:11:05 Making a Socket Connection Now that Socket.io is included in the Node application, Kyle walks through how to make a socket connection. He demonstrates the event-driven architecture by listening to connect and disconnect events on both the client and the server.
<script>
var socket = io.connect("/");
</script>
io.connect("/")
it's not a path, it's a namespace
// continue from above
socket.on("connect", function(){
console.log("connected");
})
in your server js file:
function handleIO(socket){
// "client connected"
}
io.on("connection", handleIO);
for every socket connection the handleIO
will be calledif 10 person connect to our site
hanldeIO
will be called 10 timesthen add a disconnect handler in the
handleIO
function handleIO(socket){
function disconnect(){
console.log("client disconnected");
}
socket.on("disconnect", disconnect);
}
handling disconnection on the client side (continued from the client example above)
socket.on("disconnected", function(){
console.log("disconnected");
})
to turn off verbose logging and good defaults
use
io.configure(function(){// configure socket.io})
"log level", 1
to reduce logging verbosity
// configure socket.io
io.configure(function(){
io.enable("browser client minification"); // send minified client
io.enable("browser client etag"); // apply etag caching logic based on version number
io.set("log level", 1); // reduce logging
io.set("transports", [
"websocket",
"xhr-polling",
"jsonp-polling"
]);
});