'use strict';
var express = require('express'),
path = require('path'),
logger = require('morgan'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
app = express(),
WebSocketServer = new require('ws'),
clients = {},
webSocketServer = new WebSocketServer.Server({
port: 8081
}),
msg = require("./bin/msg");
app.use(express.static('public'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
webSocketServer.on('connection', function (ws) {
var id = Math.random();
clients[id] = ws;
//console.log("новое соединение " + id);
ws.on('message', function (message) {
console.log('получено сообщение ' + message);
let msg = new Msg("кто-то", "кому-то", "Что-то", null, []);
msg.send();
for (var key in clients) {
clients[key].send(message);
}
});
ws.on('close', function () {
//console.log('соединение закрыто ' + id);
delete clients[id];
});
});
app.get("/", (req, res) => {
res.sendFile("index.html");
});
module.exports = app;
msg.js:
'use strict';
var db = require("./db"),
Schema = db.Schema;
class Msg {
constructor(from, to, text, date, ansewers) {
this.from = from;
this.to = to;
this.text = text;
this.date = date;
this.ansewers = ansewers;
}
getSchema() {
return new Schema({
from: {
type: String
},
to: {
type: String
},
text: {
type: String,
default: "..."
},
date: {
type: Date,
default: Date.now
},
});
}
getModel() {
return db.model("Msg", this.getSchema());
}
send() {
let msgModel = this.getModel();
let msg = new msgModel({
from: this.from,
to: this.to,
text: this.text
});
msg.save(function(err, msg, affected){
if(err)return err;
console.log(arguments);
});
}
}
module.exports = Msg;