socket.io-client node js example
Example 1: socket io script
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
</script>
Example 2: create a web server node js w socket.io
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.get('/', (req, res) => {
// Ran when a GET request to path '/'
res.sendFile(__dirname + '/index.html');
});
io.on('connection', (socket) => {
// Ran when a socket connected
});
http.listen(3000, () => {
// Ran when server is ready to take requestes
});
Example 3: socket.io client send data node js server
var socket = io.connect('http://localhost');
socket.emit('my other event', { my: 'data' });
//server side
io.sockets.on('connection', function (socket) {
socket.on('my other event', function (data) {
console.log(data);
});
});
//sending data from the user via a socket.io
socket.on("test", function (data) {
data.forEach(obj => {
console.log("Yer : " + obj.yer + ", Lat : " + obj.lat + ", Long : " + obj.lng);
})
});