现在我正在尝试使用套接字进行聊天,但只显示此消息。
[2017/12/08 18:51:07] WebSocket DISCONNECT / chat / prj / chat / [127.0.0.1:55457]
[2017/12/08 18:51:08] WebSocket HANDSHAKING / chat / prj / chat / [127.0.0.1:55461]
从检查员那里得到这个
InvalidStateError:尝试使用不可用或不再可用的对象 重新连接-websocket.min.js:1 Firefox无法在ws:// localhost:8000 / chat / prj / chat /建立与服务器的连接。 重新连接-websocket.min.js:1:1075 加载页面时,与ws:// localhost:8000 / chat / prj / chat /的连接中断。 重新连接-websocket.min.js:1:1075
如何解决这个问题?
这是我的consumers.py
@channel_session
def ws_connect(message):
try:
prefix, label = message['path'].strip('/').split('/')
if prefix != 'chat':
log.debug('invalid ws path=%s', message['path'])
return
room = Room.objects.get(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 path=%s reply_channel=%s',
room.label, message['client'][0], message['client'][1], message['path'], message.reply_channel)
message.reply_channel.send({"accept": True})
Group('chat-'+label, channel_layer=message.channel_layer).add(message.reply_channel)
message.channel_session['room'] = room.label
@channel_session
def ws_receive(message):
try:
label = message.channel_session['room']
room = Room.objects.get(label=label)
log.debug('recieved message, room exist label=%s', room.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
try:
data = json.loads(message['text'])
except ValueError:
log.debug("ws message isn't json text=%s", text)
return
if set(data.keys()) != set(('handle', 'message')):
log.debug("ws message unexpected format data=%s", data)
return
if data:
log.debug('chat message room=%s handle=%s message=%s',
room.label, data['handle'], data['message'])
m = room.messages.create(**data)
Group('chat-'+label, channel_layer=message.channel_layer).send({'text': json.dumps(m.as_dict())})
@channel_session
def ws_disconnect(message):
try:
label = message.channel_session['room']
room = Room.objects.get(label=label)
Group('chat-'+label, channel_layer=message.channel_layer).discard(message.reply_channel)
except (KeyError, Room.DoesNotExist):
pass
这是chat.js
$(function() {
var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
var chatsock = new ReconnectingWebSocket(ws_scheme + '://' + window.location.host + "/chat" + window.location.pathname);
chatsock.onmessage = function(message) {
var data = JSON.parse(message.data);
var chat = $("#chat")
var ele = $('<tr></tr>')
ele.append(
$("<td></td>").text(data.timestamp)
)
ele.append(
$("<td></td>").text(data.handle)
)
ele.append(
$("<td></td>").text(data.message)
)
chat.append(ele)
};
$("#chatform").on("submit", function(event) {
var message = {
handle: $('#handle').val(),
message: $('#message').val(),
}
chatsock.send(JSON.stringify(message));
$("#message").val('').focus();
return false;
});
});