adonis-websocket
adonis-websocket copied to clipboard
When an authenticated user, the websocket transmits this message: adonis: websocket connection is not in open state, current state 1 + 1ms
When an authenticated user, the websocket transmits this message: adonis: websocket connection is not in open state, current state 1 + 1ms
I am having this problem when I am logged into the application. I made the same code for when I'm logged out and works normally, following the step by step that exists in DOC.https: //adonisjs.com/docs/4.1/websocket
Can anyone explain what is missing or happening?
Package version
"version": "4.1.0",
Node.js and npm version
NODEJS = v12.16.2 NPM = 6.14.4
Code
start/socket.js
const Ws = use('Ws')
Ws.channel('chat', 'ChatController')
Ws.channel('channel', 'AdminChatController')
app/Controllers/Ws/AdminController.js
class AdminChatController {
constructor ({ socket, request }) {
this.socket = socket
this.request = request
this.message = {
username: 'Admin Chat',
body: 'Divirtam-se'
}
console.log(this.message);
this.socket.emit('message', this.message)
}
onMessage (message) {
this.socket.broadcastToAll('message', message)
}
}
module.exports = AdminChatController
public/chat.js
const CHANNEL = 'channel';
let ws = null
$(function () {
// Only connect when username is available
// if (window.username) {
// startChat()
// }
startChat()
})
function startChat () {
ws = adonis.Ws().connect()
ws.on('open', () => {
$('.connection-status').addClass('connected')
subscribeToChannel()
})
ws.on('error', () => {
$('.connection-status').removeClass('connected')
})
}
function subscribeToChannel () {
const chat = ws.subscribe(CHANNEL)
chat.on('error', () => {
$('.connection-status').removeClass('connected')
})
chat.on('message', (message) => {
console.log(message)
insertMessages(message)
})
}
function insertMessages(message) {
console.log(message);
$('.chat-list').append(`
<li>
<div class="chat-image">
<img alt="male" src="https://www.wrappixel.com/demos/admin-templates/pixeladmin/plugins/images/users/ritesh.jpg">
</div>
<div class="chat-body">
<div class="chat-text">
<h4>${message.username}</h4>
<p> ${message.body} </p>
<b>10.00 am</b>
</div>
</div>
</li>
`)
}
function sendNewMessage() {
const message = $('#message').val()
$('#message').val('')
ws.getSubscription(CHANNEL).emit('message', {
username: window.username,
body: message
})
}
$('#send-message').on('click', function() {
sendNewMessage()
})
$('#message').keyup(function (e) {
if (e.which === 13) {
e.preventDefault()
sendNewMessage()
return
}
})