loader

Logic square is a leading custom web & mobile app development company that offers its services to small businesses in the USA at an affordable cost.

Realtime Chat With Express and Faye (Bayeux Protocol)

Server Side

				
					express real-time-chat-example –ejs
cd real-time-chat-example
npm install
				
			
				
					npm install –save faye

				
			
				
					var app = require('../app');
var debug = require('debug')('faye-express:server');
var http = require('http');
var faye = require('faye'); 
var bayeux = new faye.NodeAdapter({mount: '/faye', timeout: 45}); 
var server = http.createServer(app);
bayeux.attach(server);
				
			

Client Side

				
					<head>
	<title><%= title %></title>
	<link rel=‘stylesheet’ href=‘/stylesheets/style.css’ />
	<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js”></script>
	<script type=“text/javascript” src=“http://localhost:3000/faye/client.js”></script>
	<script type=“text/javascript” src=“javascripts/script.js”></script>
</head>
				
			
				
					<body>
	<form>
		<input type=“text” id=“new-message” placeholder=“Your Message Here” />
		<input type=“submit” id=“submit-btn” value=“Enter” />
	</form>
	<h4>Messages:</h4>
	<ul id=“messages-list”>
	</ul>
</body>
				
			
				
					// Create the Faye client.
// (All you need is the mount point for the Faye server you want to connect to)
var client = new Faye.Client(‘http://localhost:3000/faye’)
$(document).ready(function () {
	$(“#submit-btn”).click(function (evt) {
		evt.preventDefault()
		var newMessage = $(“#new-message”).val()
		// We PUBLISH our new message to a CHANNEL (/messages)
		// which is dynamically “created” *in situ*, if required
		client.publish(“/messages”, {
			text: newMessage
		})
	})
	// Now we setup the client to SUBSCRIBE (listen in)
	// for messages coming into the same CHANNEL (/messages)
	// (Note that, the client which publishes the message itself is also subscribed)
	client.subscribe(“/messages”, function(newMessage) {
		$(“#messages-list”).append(“<li>” + newMessage.text + “</li>”)
	})
})
				
			

Addendum: Saving Chats on the Server

				
					var Faye = require("faye")
var client = new Faye.Client('http://localhost:3000/faye')
client.subscribe('/messages', function (newMessage) {
	console.log("New Message: ", newMessage) 
});
				
			

WE DESIGN, DEVELOP AND MARKET BEAUTIFUL WEB & MOBILE APPS

Author

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *