2016-08-13 96 views
1

我一直試圖在我的AWS EC2服務器上使用端口1883設置MQTT代理。到目前爲止,它與ruby-mqtt gem一起工作,但我在使用Paho Javascript Client進行網站設置時遇到了麻煩。在AWS EC2上設置帶有mosquitto的Paho Javascript客戶端(MQTT)Ubuntu + Ruby on Rails

我迄今所做的:

Mosquitto

我的AWS EC2實例

安裝mosquitto,並在運行並監聽端口1883我訂閱的話題在本地使用命令

mosquitto_sub -h localhost -p 1883 -v -t 'topic1' 

AWS EC2安全組

允許通過端口1883(在TCP協議)業務

Ruby on Rails的

安裝紅寶石MQTT寶石,並測試了MQTT通過在導軌控制檯(開發環境)

運行下面的代碼來工作
MQTT::Client.connect(ip_address_or_domain_name) do |c| 
    c.publish('topic1', 'message to topic 1') 
end 

該消息出現在正在運行mosquitto_sub的終端中。

Nginx的

所有這一切都沒有在Nginx的配置文件的任何配置來完成。

泛美衛生組織客戶

所以我啓動了一個本地服務器導軌我的本地計算機上,並在我的HTML視圖的一個運行示例JavaScript代碼段。

// Create a client instance 
client = new Paho.MQTT.Client("mqtt.hostname.com", Number(1883), "", "clientId") 

// set callback handlers 
client.onConnectionLost = onConnectionLost; 
client.onMessageArrived = onMessageArrived; 

// connect the client 
client.connect({onSuccess:onConnect}); 


// called when the client connects 
function onConnect() { 
    // Once a connection has been made, make a subscription and send a message. 
    console.log("onConnect"); 
    client.subscribe("topic1"); 
    message = new Paho.MQTT.Message("Hello"); 
    message.destinationName = "topic1"; 
    client.send(message); 
} 

// called when the client loses its connection 
function onConnectionLost(responseObject) { 
    if (responseObject.errorCode !== 0) { 
    console.log("onConnectionLost:"+responseObject.errorMessage); 
    } 
} 

// called when a message arrives 
function onMessageArrived(message) { 
    console.log("onMessageArrived:"+message.payloadString); 
} 

但我無法連接。我在鉻開發者控制檯中得到的錯誤是:

WebSocket connection to 'ws://mqtt.example.com:1883/' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET 

林不知道這裏有什麼問題。非常感謝任何幫助!提前致謝!

回答

1

所以問題是泛美衛生組織JavaScript客戶端指出,對於client對象的參數必須

的郵件服務器的地址,作爲完全合格的WebSocket URI,爲DNS名稱或點分十進制IP地址。

因此,讓它監聽端口1883,這是mqtt的標準端口,將無法正常工作。

ruby-mqtt作品這是因爲它參數作爲一個MQTT URI

換句話說處理,經由Paho連接ws://hostruby-mqtt經由mqtt://host連接。後者使用正確的協議連接到端口1883(不確定這是否是正確的字),以確保 正確的端口。

因此Paho必須連接到可以使用websocket協議的另一個端口。

這是我的解決方案。

Mosquitto

版本必須至少爲1.4,是支持WebSocket的。我將最後3行添加到默認的mosquitto.conf文件中。

# /etc/mosquitto/mosquitto.conf 
pid_file /var/run/mosquitto.pid 

persistence true 
persistence_location /var/lib/mosquitto/ 

log_dest file /var/log/mosquitto/mosquitto.log 

include_dir /etc/mosquitto/conf.d 

port 1883 

listener 1884 
protocol websockets 

這將打開2端口蚊子分別訂閱超過2個不同的協議。

AWS安全組

允許通信和通過端口1884(在TCP協議)

PAHO客戶

mqtt.hostname.com 變化只是其中客戶對象是線初始化爲

client = new Paho.MQTT.Client("mqtt.hostname.com", Number(1884), "", "clientId") 
+0

你的蚊子to.conf真是太棒了! Thx – domih

+0

:)好我可以幫忙 – Vic