moscajs / mosca

MQTT broker as a module
mosca.io
3.2k stars 513 forks source link

Something gets wrong in mqtt-over-websocket #669

Closed grath10 closed 6 years ago

grath10 commented 6 years ago

When trying to copy the example code of client side from the page https://github.com/mcollina/mosca/wiki/MQTT-over-Websockets , I got this message in the console: mqtt.js:1 WebSocket connection to 'ws://localhost:3000/' failed: Connection closed before receiving a handshake response WebSocketStream | @ | mqtt.js:1

Besides, a node HTTP server has been augmented with MQTT-over-websocket capabilities, scripts run in node.js can connect to the broker successfully. However, it seems that when in the browser enviroment, trouble appears as illustrated above. Can anyone provide any idea about how to solve this problem? Tips: mqtt.js is obtained from https://unpkg.com/mqtt/dist/mqtt.min.js. and renamed to mqtt.js by myself.

mcollina commented 6 years ago

Can you post a minimal snippet of your broker code to reproduce the issue?

grath10 commented 6 years ago

Express Web Project: app.js var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser');

var index = require('./routes/index');

var app = express();

var mosca = require("mosca"), mqttServ = new mosca.Server({}); var http = require("http"), httpServ = http.createServer(app);

// view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs');

mqttServ.attachHttpServer(httpServ);

// uncomment after placing your favicon in /public //app.use(favicon(path.join(dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(dirname, 'public')));

app.use('/', index); module.exports = app;

==================== index.ejs

<%= title %>
mcollina commented 6 years ago

Are you connecting with MQTT.js over WebSocket, and it is working? Are you using NGINX or something else in-between?

grath10 commented 6 years ago

To reply, no nginx or other else in-between and it is working if the whole program is in pure node.js without web frames like Express. The problem may lie in this place: var client = mqtt.connect(); if I change to var client = mqtt.connect("ws://test.mosca.io");, the program runs normally, however, if no parameter is set like mqtt.connect(), the problem arises. Is there anything more I need to make the program run normally, appreciated very much for any help!

mcollina commented 6 years ago

where are you calling httpServ.listen(3000)?