Created
October 27, 2018 09:25
-
-
Save aditodkar/90dcb885f8db22fbccdacce6605645b0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const express = require('express'); | |
| const mongoose = require('mongoose'); | |
| const socket = require('socket.io'); | |
| const message = require('./model/message') | |
| const app = express(); | |
| const db = require('./config/keys').mongoURI; | |
| mongoose.connect(db, {useNewUrlParser: true}) | |
| .then( | |
| io.on("connection", function(socket){ | |
| console.log("Socket Connection Established with ID :"+ socket.id) | |
| socket.on('disconnect', function(){ | |
| console.log('User Disconnected'); | |
| }); | |
| let chat = db.collection('chat'); | |
| socket.on('SEND_MESSAGE', function(data){ | |
| let message = data.message; | |
| let date = data.date; | |
| // Check for name and message | |
| if(name !== '' || date !== ''){ | |
| // Insert message | |
| chat.insert({message: message, date:date}, function(){ | |
| socket.emit('output', [data]); | |
| }); | |
| } | |
| }); | |
| chat.find().limit(100).sort({_id:1}).toArray(function(err, res){ | |
| if(err){ | |
| throw err; | |
| } | |
| // Emit the messages | |
| socket.emit('RECEIVE_MESSAGE', res); | |
| }); | |
| }) | |
| ) | |
| .catch( err => console.log(err)); | |
| const port = 5000; | |
| let server = app.listen(5000, function(){ | |
| console.log('server is running on port 5000') | |
| }); | |
| let io = socket(server); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment