Wednesday, November 23, 2016

Help!! After a while Django no longer send information to client

Here is My Django code

@channel_session
def ws_connect(message):
    # Extract the room from the message. This expects message.path to be of the
    # form /chat/{label}/, and finds a Room if the message path is applicable,
    # and if the Room exists. Otherwise, bails (meaning this is a some othersort
    # of websocket). So, this is effectively a version of _get_object_or_404.
    try:
        # prefix, label = message['path'].decode('ascii').strip('/').split('/')
        prefix, label = message['path'].strip('/').split('/')
        if prefix != 'chat':
            log.debug('invalid ws path=%s', message['path'])
            return
        room, created = Room.objects.get_or_create(label=label)
    except ValueError:
        log.debug('invalid ws path=%s', message['path'])
        return
    except Room.DoesNotExist:
        log.debug('ws room does not exist label=%s', label)
        return

    log.debug('chat connect room=%s client=%s:%s',
              room.label, message['client'][0], message['client'][1])

    # Need to be explicit about the channel layer so that testability works
    # This may be a FIXME?
    Group('chat-' + label, channel_layer=message.channel_layer).add(message.reply_channel)

    message.channel_session['room'] = room.label


@channel_session
def ws_receive(message):
    # Look up the room from the channel session, bailing if it doesn't exist
    try:
        label = message.channel_session['room']
        room = Room.objects.get(label=label)
    except KeyError:
        log.debug('no room in channel_session')
        return
    except Room.DoesNotExist:
        log.debug('recieved message, buy room does not exist label=%s', label)
        return

    # Parse out a chat message from the content text, bailing if it doesn't
    # conform to the expected message format.
    try:
        # data = json.loads(message['bytes'].decode(errors='replace'))
        tcl_json_info = message['bytes'].decode('utf-8', errors="replace").strip()
        tcl_json_info = tcl_json_info.replace("\n", "\\n")
        tcl_json_info = tcl_json_info.replace("\r", "\\r")
        tcl_json_info = tcl_json_info.replace("\t", "\\t")
        # data = json.loads(tcl_json_info)
        data = ast.literal_eval(tcl_json_info)
    except ValueError:
        log.debug("ws message isn't json binary=%s", data)
        return

    if set(data.keys()) != set(('newline', 'mf', 'message', 'level', 'timestamp', 'color', 'type')):
        log.debug("ws message unexpected format data=%s", data)
        return

    if data:
        log.debug('chat message room=%s timestamp=%s newline=%s mf=%s level=%s color=%s type=%s message=%s',
                  room.label, data['timestamp'], data['newline'], data['mf'], data['level'], data['color'], data['type'], data['message'])
        # with transaction.atomic():
        #     m = room.messages.create(**data)
        # m = room.messages.create(**data)

        # See above for the note about Group
        # Group('chat-' + label, channel_layer=message.channel_layer).send({'text': json.dumps(m.as_dict())})
        Group('chat-' + label, channel_layer=message.channel_layer).send({'text': json.dumps(data)})




Here is my javascript code:

    ws.onopen = function (evt) {

      var keepAliveMsg = {newline: '1', mf: '0',message: '',level: 'info',timestamp: '0',color: 'black',type: 'buffer'};

      // var byteArray = new Uint8Array(keepAliveMsg);
      var blob = new Blob([JSON.stringify(keepAliveMsg)]);

      ws.interval_event = $interval(function () {
        ws.send(blob);
      }, 5000)
    };


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/a0264ee9-1201-4fb7-aaca-35218cca41ae%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment