server.js :-
const http = require(‘http’)
const express = require(‘express’)
const app = express()
const socketio = require(‘socket.io’)
const server = http.createServer(app)
const io = socketio(server)
io.on(‘connection’ , (socket)=>{
//this function takes a socket argument and connects it to the socket id
console.log("Connected with socket id= ", socket.id)
socket.on('boom', ()=>{
//this function will run if the boom event happens
console.log('boom received from ', socket.id)
})
setInterval(() =>{
//emit whizzz after every 2sec
socket.emit('whizzz')
},2000)
})
app.use(’/’, express.static(__dirname + ‘public’))
server.listen(3344,()=>{
console.log(‘Started on http://localhost:3344’)
})
public>index.html:-
Document <script src="/socket.io/socket.io.js"></script>
<script defer src="script.js"></script>
</head>
<body>
<h1>Socket.IO Sample</h1>
<button id="boom">Boom</button>
</body>
public > script.js
let socket = io()
let boombtn = document.getElementById(‘boom’)
boombtn.onclick = function() {
socket.emit(‘boom’)
//socket.emit -> so as to emit events into a socket
socket.on('boom', () => {
console.log('boom received from ', socket.id)
})
}
ERROR:-
/usr/local/bin/node Client_to_sever/public/script.js
/Users/deeptisharma/Desktop/socketIO /Client_to_sever/public/script.js:1
let socket = io()
^
ReferenceError: io is not defined
at Object. (/Users/deeptisharma/Desktop/socketIO /Client_to_sever/public/script.js:1:14)
at Module._compile (internal/modules/cjs/loader.js:1138:30)
at Object.Module._extensions…js (internal/modules/cjs/loader.js:1158:10)
at Module.load (internal/modules/cjs/loader.js:986:32)
at Function.Module._load (internal/modules/cjs/loader.js:879:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47