Advertisement
Guest User

Server.js

a guest
Nov 2nd, 2018
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. import * as ws from "nodejs-websocket";
  2. import { Message } from "./Message";
  3.  
  4. class Server {
  5. constructor() {
  6. this.participants = new Map();
  7.  
  8. this.server = ws.createServer(conn => {
  9. conn.on("text", text => {
  10. const msg = Message.fromString(text),
  11. method = `on${msg.event}`;
  12. if (!this[method]) {
  13. return;
  14. }
  15. this[method](msg.data, conn);
  16. });
  17.  
  18. conn.on("error", err => {
  19. console.error("Server error:", err);
  20. });
  21.  
  22. conn.on("close", (code, reason) => {
  23. console.log("Server closed a connection", code, reason);
  24. });
  25.  
  26. conn.on("connection", () => {
  27. console.info("Server creates a new connection");
  28. });
  29. });
  30. }
  31.  
  32. onjoin(name, conn) {
  33. const datetime = new Date();
  34. this.participants.set(conn, {
  35. name: name,
  36. time: datetime.toString()
  37. });
  38. this.broadcast("participants", Array.from(this.participants.values()));
  39. }
  40.  
  41. ontext(data, conn) {
  42. const name = this.participants.get(conn).name;
  43. this.broadcast("text", { name, ...data });
  44. }
  45.  
  46. broadcast(event, data) {
  47. const text = Message.toString(event, data);
  48. this.server.connections.forEach(conn => {
  49. conn.sendText(text);
  50. });
  51. }
  52.  
  53. connect(host, port, client) {
  54. client
  55. .connect(
  56. host,
  57. port
  58. )
  59. .catch(() => {
  60. this.server.listen(port, host, () => {
  61. console.log(`Server listening on port ${port}`);
  62. client
  63. .connect(
  64. host,
  65. port
  66. )
  67. .catch(() => {
  68. console.log("Client's error!");
  69. });
  70. });
  71. });
  72. }
  73. }
  74.  
  75. export default Server;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement