Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const WebSocket = require('ws')
- const redis = require('redis')
- const response = require('../response.js');
- const redis_schema = require('../redis_schema.js');
- clients = new Map()
- const wss = new WebSocket.Server({
- host: "localhost",
- port: 3226,
- clientTracking: true
- });
- const db_user = 1;
- var db = redis.createClient();
- db.select(db_user, (err,res) => {
- console.log(`Switching to 1 db = ${res}`);
- });
- db.on('connect', () => {
- console.log('Сonnected to Redis');
- });
- const close_ws_connection = (ws)=> {
- redis_schema.set_user_properties(db, clients.get(ws));
- console.log(`Connection with user: ${clients.get(ws)} id has been closed`);
- }
- const on_message = (ws, message) =>{
- try{
- var user = JSON.parse(message);
- if(user.user_id === undefined){
- let error = "Error! User_id has not been passed";
- console.log(error);
- let rsp = new response.OrdinaryResponse(true, error);
- ws.send(JSON.stringify(rsp));
- return;
- }
- else{
- console.log(`User has been connected with id ${user.user_id}`);
- clients.set(ws, user.user_id);
- redis_schema.set_user_properties(db, user.user_id, true, false);
- find_game(ws);
- return;
- }
- }
- catch(err){
- let error = "Invalid request";
- console.log(err);
- let rsp = new response.OrdinaryResponse(true, error);
- ws.send(JSON.stringify(rsp));
- return;
- }
- }
- wss.on('connection', (ws) => {
- ws.on('close', () => {
- close_ws_connection(ws);
- })
- ws.on('message', (message) => {
- on_message(ws, message);
- })
- })
- const find_game = (ws) =>{
- console.log(clients.get(ws));
- const connection = new WebSocket("ws://localhost:3227");
- connection.onclose = () => {
- let error = "Manager anavailable";
- let rsp = new response.OrdinaryResponse(false, error);
- for (let client of clients){
- client[0].send(JSON.stringify(rsp));
- }
- }
- connection.onerror = () => {
- let error = "Manager anavailable";
- let rsp = new response.OrdinaryResponse(false, error);
- for (let client of clients){
- client[0].send(JSON.stringify(rsp));
- }
- }
- connection.onopen = () => {
- try{
- data = {
- "user_id":clients.get(ws)
- }
- connection.send(JSON.stringify(data));
- return;
- }
- catch(err){
- console.log(`Error ${err}`);
- return;
- }
- }
- connection.onmessage = (e) => {
- data = JSON.parse(e.data);
- let current_client_id = clients.get(ws);
- if(data.pair_id !== undefined && data.pair_id !== current_client_id){
- for (let client of clients) {
- if(client[1] == data.pair_id){
- let game_info = new response.GameInfo(data.host, data.port, current_client_id);
- redis_schema.set_user_properties(db, data.pair_id, true, true);
- client[0].send(JSON.stringify(game_info));
- }
- }
- }
- ws.send(e.data);
- return;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement