M
M
MichaelMih2021-07-06 00:27:09
Flask
MichaelMih, 2021-07-06 00:27:09

Client is gone, closing socket how to fix?

Good afternoon! Does not accept sockets.

python
from flask import session, request
from flask_socketio import emit, join_room, namespace
from .. import socketio
from .. import database
import random
import string
from datetime import datetime


@socketio.on('bet', namespace='/app/auction')
def new_bet(json):
    check_acc = database.check_acc_password_id(session['user_login'], session['user_password'], session['user_id'])
    if check_acc[0] == False or int(check_acc[1]['score']) < 50:
        print("err")
        emit("error_bet", {}, namespace='/app/auction')
        return
    database.update_row("users", f"id = {session['user_id']}", score=int(check_acc[1]['score']) - 50)
    database.auction_update(session['user_id'], 50)
    now = datetime.now().strftime("%d.%m.%Y %H:%M:%S")
    database.update_row("timer", start_time=now, active=1)
    d = database.get_row("auction", check=f"user_id={session['user_id']}")
    summ = 0
    if len(d) != 0:
        summ =  d[0]['summ']
    respones = {"name": session['user_login'], "summ": summ}
    emit("add_bet", respones, namespace='/app/auction', room=1)
    emit("update_score", {'score': check_acc[1]['score']}, namespace='/app/auction')

@socketio.on("get_time", namespace="/app/auction")
def get_time_auction(json):
    time = database.get_row("timer")[0]
    if time['active'] == "0":
        socketio.emit("second", {'second': -1})
    if time['start_time'] == "0":
        now = datetime.now().strftime("%d.%m.%Y %H:%M:%S")
        database.update_row("timer", start_time=now)
    a = time['active']
    time = datetime.strptime(time['start_time'], "%d.%m.%Y %H:%M:%S")
    time_2 = datetime.now()
    response_time = time_2 - time 
    response_time = 10 - response_time.seconds
    socketio.emit("second", {'second': response_time, "active": a}, namespace='/app/auction')

@socketio.on('end_auction_timer', namespace='/app/auction')
def end_time_auction(json):
    database.update_row("timer", active=0)
    database.auction_end()


@socketio.on('new_message', namespace="/app/auction")
def message(json):
    time = datetime.now().strftime("%d.%m.%Y %H:%M:%S")
    img = database.get_row("users", 'image', "id=%s", session['user_id'])
    database.add_row("messages", user_id=session['user_id'], user_login=session['user_login'], message=json['text'], time=time, image=img[0])
    respones = {"name": session['user_login'], "text":json['text'], "img": img, "time": time}
    emit("message", respones, namespace='/app/auction', room=1)

@socketio.on("join", namespace='/app/auction')
def connect_auction(json):
    join_room(1)


@socketio.on("task_success", namespace='/app/task')
def fdsf(json):
    print(json)
    socketio.emit("success_task", {"status": "success", "summ": 4}, namespace='/app/task')

js
var alert_timeout = 3000;
var socket = io.connect(
  "http://" + document.domain + ":" + location.port + "/app/auction"
);
var timer = 0;

$(document).ready(function () {
  $('#msg').keypress(function(e){
    if(e.keyCode==13)
    $('#send_message').click();
  });
  $('.chat-msg').scrollTop($('.chat-msg')[0].scrollHeight); 

  socket.on("connect", () => {
    socket.emit("join", {});
    socket.emit("get_time", {});
  });

  socket.on("error_bet", () => {
    console.log("err");
    view_alert("Не удалось поставить ставку!");
  });

  $(".auction-button").click(function () {
    socket.emit("bet", {});
  });

  socket.on("add_bet", function (msg) {
    display_score = $(".auction-summ-score");
    var score = parseInt(display_score.text()) + 50; 
    $("#last-auction-name").text(msg['name']);
    $("#last-auction-summ").text(msg['summ']);
    display_score.text(score);
    socket.emit("get_time", {});
  });

  socket.on("update_score", function(msg) {
    $("#user_score").text(msg['score']);
  });

  socket.on("second", function (msg) {
    console.log(msg);
    if (msg['active'] == "1") { 
      clearInterval(timer);  
      auction_bet(msg['second']);
    }
  });

  $("#send_message").click(function (e) {
    console.log("click");
    socket.emit("new_message", {text: $("#msg").val()})
    $("#msg").val("");
  });

  socket.on('message', function (msg) {
    add_msg(msg['name'], msg['time'], msg['text'], msg['img']);
  });

});


function add_msg(name, time, text, img) {
  $( ".chat-msg" ).append( `<div class="chat-message">
  <div class="message-photo"><img src="${img}"></div>
  <div class="message-text">
      <div class="message-text-header">
          <div class="message-name">${name}</div>
          <div class="message-time">${time}</div>
      </div>
      <div class="message-msg">${text}</div>
  </div>
</div>`);
$('.chat-msg').scrollTop($('.chat-msg')[0].scrollHeight); 
}

function auction_bet(timeLeft) {
  var display = $("#timer"); // меняющаяся цифра
  var head = $(".auction-timer-head");
  $('.auctiom-timer-time').addClass("active");
  timer = setInterval(function () {
    timeLeft == --timeLeft;
    if (timeLeft >= 0) {
      // если таймер всё еще больше нуля
      display.text(timeLeft); // обновляем цифру
    } else {
      $('.auctiom-timer-time').removeClass("active");
      $('.auction-summ-score').text("0");
      $("#last-auction-name").text("нет");
      $("#last-auction-summ").text("0");
      socket.emit("end_auction_timer", {})
      clearInterval(timer); // удаляем таймер
    }
  }, 1000); // таймер срабатывает каждые 1000 msec (1 sec)
}

function view_alert(text) {
  $(".alert").toggleClass("active");
  $(".alert p").text(text);
}


Socket version: 3.1.3
Everything works in version 1.3.6.
Flask socketio: 4.3.1

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question