Implementing socket connection between NodeJS and AngularJS
Posted By : Vivek Joshi | 02-Sep-2017
For Implementing socket connection between client and server using nodejs these are the steps
Step 1:- First we have to create a socket server in server side using socket.io package of nodejs
Step 2:- Download socket.io package.
npm install socket.io
Step 3:- Using with expressjs module create server socket connection
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(8080);
io.on('connection', function (socket) {
console.log('A user connected');
//Whenever someone disconnects this piece of code executed
socket.on('disconnect', function () {
console.log('A user disconnected');
});
socket.on('message', function (message) {
console.log("message received""+message);
});
socket.broadcast.emit("sendMessage", "message from server");
})
Step 4:- Create click side connection and send or receive message from server.
client (index.html)
<script src="/socket.io/socket.io.js">
<!--make sure that client app and server app is running in same port if not then add dependency with hole url e.g (src="http://www.abc.com/socket.io/socket.io.js"-->
</script>
<script>
//if click and server not running in same port then specify port also e.g 'http://localhost:8080'
var socket = io.connect('http://localhost');
socket.on('sendMessage', function (data) {
//receive message from server or other clickt who is emiting with name 'sendMessage'
console.log(data);
});
//this is use for sending message from the client to server or other client with is listing this message
socket.emit('message',"send message from client" );
</script>
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Vivek Joshi
Vivek is Web App Developer in Java Technology and also working on NodeJS.