index.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. var app = require("express")();
  2. var http = require("http").Server(app);
  3. var io = require("socket.io")(http);
  4. const cors = require("cors");
  5. app.use(cors());
  6. app.get("/", function (req, res) {
  7. res.sendFile(__dirname + "/index.html");
  8. });
  9. io.on("connection", function (socket) {
  10. console.log("an user connected with id", socket.id);
  11. io.emit("msg", {
  12. nick: "--Администрация--",
  13. message: `у нас новенький (socket.id: ${socket.id})`,
  14. });
  15. socket.on("msg", function (msg) {
  16. if (msg && msg.message && msg.nick) {
  17. io.emit("msg", msg);
  18. } else {
  19. console.log("WRONG MESSAGE", msg);
  20. }
  21. });
  22. socket.on("disconnect", function () {
  23. console.log("user disconnected " + socket.id);
  24. io.emit("msg", {
  25. nick: "--Администрация--",
  26. message: `пользователь покинул чат (socket.id: ${socket.id})`,
  27. });
  28. });
  29. });
  30. http.listen(4000, function () {
  31. console.log("listening on *:4000");
  32. });