Broker
var mosca = require('mosca')
var settings = {
port: 1884
};
//here we start mosca
var server = new mosca.Server(settings);
server.on('ready', setup);
// fired when the mqtt server is ready
function setup() {
console.log('Mosca server is up and running')
}
// fired whena client is connected
server.on('clientConnected', function(client) {
console.log('client connected', client.id);
});
// fired when a message is received
server.on('published', function(packet, client) {
if (packet.cmd === 'publish') {
//Qui uso mongo DB
console.log('Published: ', packet.payload.toString('utf8'));
}
});
// fired when a client subscribes to a topic
server.on('subscribed', function(topic, client) {
console.log('subscribed : ', topic);
});
// fired when a client subscribes to a topic
server.on('unsubscribed', function(topic, client) {
console.log('unsubscribed : ', topic);
});
// fired when a client is disconnecting
server.on('clientDisconnecting', function(client) {
console.log('clientDisconnecting : ', client.id);
});
// fired when a client is disconnected
server.on('clientDisconnected', function(client) {
console.log('clientDisconnected : ', client.id);
});
client.html
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<script src="./mqttws3.1.js"></script>
<script>
var client = new Paho.MQTT.Client( 'localhost', 1884, 'clientId');
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
client.connect({onSuccess:onConnect});
function onConnect() {
// Once a connection has been made, make a subscription and send a message.
console.log("onConnect");
client.subscribe("/World");
message = new Paho.MQTT.Message("Hello");
message.destinationName = "/World";
client.send(message);
};
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0)
console.log("onConnectionLost:"+responseObject.errorMessage);
};
function onMessageArrived(message) {
console.log("onMessageArrived:"+message.payloadString);
client.disconnect();
};
</script>
</body>
</html>
I run the broker
node broker
than I call the client.html by a web server
like
http://localhost/client.html
I get after a while
Firefox can't establish a connection to the server at
ws://localhost:1884/mqtt. this.socket = new WebSocket(wsurl,
["mqtt"]);
Chrome : WebSocket connection to 'ws://localhost:1884/mqtt' failed:
WebSocket opening handshake timed out
I don't know which way to turn :(
Can you help me please ?
Have a look at this:
https://github.com/mcollina/mosca/wiki/MQTT-over-Websockets
It looks like you have just started a normal MQTT listener not a WS listener.
You need to add a http block to the settings:
var settings = {
http: {
port: 1884,
bundle: true,
static: './'
}
};
Related
I have a react native 0.59 app with nodejs 10.2 as backend. The socket.io 2.2.0 running on a server and it is 2.1.1 running on the app client. Here is the socket related code:
Nodejs server:
All socket.io related code is in the index.js file:
io.on('connection', (socket) => {
console.log("socket.id : ", socket.id);
socket.on('message', (msg) => {
console.log("msg received by server socket : ", msg);
});
console.log("Socketio server is initialized");
//disconnect
socket.on('disconnect', async function() {
try {
await SocketList.update({
active: false
}, {
where: {socket_id: isocket.id}
});
} catch(err) {
console.log("err in false socket id", socket.id);
}
console.log('disconnected event');
});
});
A listener for message is implemented.
React Native App:
The socket.io client used is 2.1.1. The socket is initiated in App.js and pass to Chat component. In the Chat component, connect is made with the socket to the server and emit a message:
App.js:
//socket.io
const socket = io(GLOBAL.BASE_URL, {
transports: ['websocket'],
jsonp: false
});
let props = {
eventId: "",
user: ""
};
const ChatWithSocket = (props) => (<Chat {...props} socket={socket} />)
//create the navigator
const navigator = createStackNavigator(
{
Event: Event,
Chat: {
screen: ChatWithSocket,
}
}, {
initialRouteName: "Event"
}
);
Component Chat.js:
When user enter a chat message and click send, The socket fires up the connect and emit a message with the message entered by the user:
_onSend(messages = []) {
console.log("socket.io in chat _onSend : ", this.props.socket.id);
this.props.socket.connect();
this.props.socket.on('connect', () => {
socket.emit("message", {msg: messages[0].text});
});
this.setState(previousState => ({
messages: GiftedChat.append(previousState.messages, messages),
}))
}
The problem is after the chat message is sent from the app, there is no response from the server and the following socket listener code is not executed:
socket.on('message', (msg) => {
console.log("msg received by server socket : ", msg);
});
Here is the console output (portion) on Nodejs server:
Listening on port 3000...
Executing (default): SELECT 1+1 AS result
DB connection has been established successfully.
socket.id : U0Vm-O5ainh-IRusAAAA
Socketio server is initialized
err in false socket id U0Vm-O5ainh-IRusAAAA
disconnected event
socket.id : 7qo9ncTog0dhPfL6AAAB
Socketio server is initialized
The initial socket connection was closed and the socket 7qo9ncTog0dhPfL6AAAB is initiated again.
Here is the app console output showing 2 messages have been sent by client 7qo9ncTog0dhPfL6AAAB which matches the socket.id on the server:
4-14 22:21:19.034 26574 26634 I ReactNativeJS: 'socket.io in chat _onSend : ', '7qo9ncTog0dhPfL6AAAB'
04-14 22:21:24.286 26574 26634 I ReactNativeJS: 'socket.io in chat _onSend : ', '7qo9ncTog0dhPfL6AAAB'
Id like to auth eacht socket.io event on server side.
When i open angular page first, call method initSocket(login: Login), its ok.
Authentification successfull and i can send a message to server.
But if i restart server, angular reconnect to server by Htttp, but cant send a message by socketio.
In my server no messages in logs.
It seems that socketio-jwt block an clients message.
If i press F5 on client side its still ok again.
How to solve it without refreshing a page?
It seems taht i have to pass a token to each event on client side, after connection established to, but i dont know how to do it.
Angular 6:
public initSocket(login: Login): void {
this.socket = socketIo(SERVER_URL);
console.log('Socket init at' + SERVER_URL);
this.socket.emit('authenticate', { token: this.login.token });
this.socket.on('authenticated', function () {
console.log('socket is jwt authenticated');
});
this.socket.on('unauthorized', function (error, callback) {
if (error.data.type === 'UnauthorizedError' || error.data.code === 'invalid_token') {
// redirect user to login page perhaps or execute callback:
callback();
console.error('Users token has expired');
}
});
this.socket.on('disconnect', function (error) {
console.error('socket disconnect', error);
});
this.socket.on('connect_failed', function (error) {
console.error('socket connect_failed');
});
}
Server side:
io.sockets
.on('connection', socketioJwt.authorize({
secret: environment.secret,
timeout: 15000,
callback: false
})).on('authenticated', function (socket) {
clients[socket.decoded_token.id] = socket.decoded_token.login;
console.error('Connected: ', socket.decoded_token.login);
socket.on('message', async function (data) {
try {
// Проверка что пользователь пишите от себя
if (data.from === socket.decoded_token.id) {
data.totalCount = await db_helper.saveMessage(data);
if (clients[data.from] && clients[data.to]) {
io.sockets.connected[clients[data.to].socket].emit("message", data);
console.log("Sending from: " + clients[data.from].name + " to: " + clients[data.from].name + " '" + data.text + "'");
} else {
console.log('User does not exist: from=>', data.from, ':', clients[data.from], 'to=>', data.to, ':', clients[data.to]);
}
}
}
catch (error) {
console.error(error.message);
}
});
//Removing the socket on disconnect
socket.on('disconnect', function () {
});
});
This is because whenever your server/client goes offline, a new socket is created for re connection purpose and to establish a new connection i.e re connection, Server disconnects all it's previous connection from the same client, this process is asynchronous and thus is not visible to developers easily.
I would have also checked if my socket reconnection which is done is reconnected to the , by default socket reconnects to the port your client is connected to.
if that's the case then you need to reconnect with the help of io (socket manager)
There is also a possibility that your client re connection is set to false, you can check your socket properties by consoling it as follows:
this.socket.on('disconnect', function (error) {
console.log('disconnected', this)
//this sets whether the re connection is allowed or not
this.io._reconnection = true;
});
this.socket.on('reconnect', (error, callback) => {
console.log('reconnect succesfully', this);
//connect to the previously connected socket.
this.io.socket.reconnect()
});
am connecting xml socket to node.js websocket. Its showing connect message first. When a message send to server, its showing socket close error.
import flash.net.XMLSocket;
var client_socket: XMLSocket = new XMLSocket();
client_socket.connect("localhost",8080);
client_socket.addEventListener(DataEvent.DATA, on_serverData);
client_socket.addEventListener(Event.CONNECT, on_serverConnection);
client_socket.addEventListener(IOErrorEvent.IO_ERROR,IOerror);
client_socket.addEventListener(Event.CLOSE,socketclose);
client_socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR,socketsecurityerror);
function socketsecurityerror(event:SecurityErrorEvent)
{
trace("socketsecurityerror");
}
function IOerror(event : IOErrorEvent):void
{
trace("IOerror");
}
function socketclose(event : Event):void
{
trace("socketclose");
}
function on_serverConnection(event:Event)
{
trace("connected");
var o :Object= new Object();
o.hello = "initial_start" ;
// client_socket.send(JSON.stringify(o));
}
function on_serverData(event:DataEvent)
{
trace("errorrrrrrrrrr"+event.target.data);
}
What could be the issue, as its showing connect message and socketclose error only while sending data to websocket.
The below code is my websocket server.
var WebSocketServer = require('ws').Server
, wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws)
{
ws.on('message', function incoming(message) {
});
ws.on('close', function() {
});
ws.on('error', function() {
});
});
Will it be an issue with xmlsocket and websocket communication?
Thanks
XMLSocket cannot connect to a Websocket.
Websockets have a handshake and a protocol (see https://www.rfc-editor.org/rfc/rfc6455), whereas XMLSocket is just for sending and receiving XML data.
If you want to use websockets in AS3, try something like https://github.com/theturtle32/AS3WebSocket
i am trying to do a very simple real time notification with socket.io. for some reason i can't receive data or fire the event from server to client but from client to server yes. let me show my code:
Client Side
ngOnInit() {
this.socket.on('connect', function (res: any) {
console.log('Socket.io is connected on client side!'); // it shows on client console
});
this.socket.on('alarmsreceived', function (res: any) {
console.log(res + ' i am here now'); // is not firing
});
}
// this method fires from a click button
objectStatus = () => {
this.socket.emit('alarmsystem', 'i am client going to server');
}
Server
var io = require('socket.io').listen(server);
var connections = [];
io.of('/api/v1/monitoring').on('connect', function(socket){
connections.push(socket);
console.log('Connected %s sockets', connections.length); // i see connection on cmd
socket.on('disconnect', function() {
connections.splice(connections.indexOf(socket), 1);
console.log('Connected %s sockets', connections.length);
});
socket.on('alarmsystem', function(res) {
console.log(res); // this shows me the message from client
io.sockets.emit('alarmsreceived', 'I am server heading to client');
});
})
it seems pretty straight forward, but not firing the client event. Can someone help me what i am doing wrong here? Thanks in advance
Below is the websocket server side code that uses "ws" plugin.
var WebSocketServer = require('ws').Server
,wsSend = new WebSocketServer({port: 8080}) //Client sends message on this port.
,wsReceive = new WebSocketServer({port: 8081}) //Response is sent on this port.
,clientMessage;
wsSend.on('connection', ReceiveSocketConnection);//From client.
//Callback function on connection with client.
function ReceiveSocketConnection(webSocket) {
webSocket.on('message', GetMessageFromClient);
}
//Handler to receive message from client.
function GetMessageFromClient(messageFromClient) {
clientMessage = messageFromClient; //Message from client saved into variable
}
wsReceive.on('connection', SendSocketConnection);//To client.
function SendSocketConnection(webSocket) {
webSocket.send(clientMessage);//Here clientMessage is undefined
}
Below is the client side code.
var WebSocket = require('ws')
, wsSend = new WebSocket('ws://localhost:8080') //send port
, wsReceive = new WebSocket('ws://localhost:8081'); //receive port
//Open connection on send port.
wsSend.on('open', function() {
wsSend.send('Hi I am new to websockets');
});
//Open connection on receive port.
wsReceive.on('open', function() {
//Do nothing
});
//Receive message from server via port 8081
wsReceive.on('message', function(message) {
console.log('received: %s', message);
});
Separate ports for sending and receiving messages are there because it is a design decision.
I want to echo the message by receiving it on one port and sending it on another.
Problem : The message from the client is not saved into the local variable(i.e clientMessage).Any suggestions?
this should work, however i recommend using http://socket.io/
var WebSocketServer = require('ws').Server
,wsSend = new WebSocketServer({port: 8080}) //Client sends message on this port.
,wsReceive = new WebSocketServer({port: 8081}) //Response is sent on this port.
wsReceive.broadcast = function(data) {
for(var i in this.clients)
this.clients[i].send(data);
};
wsSend.on('connection', function(ws) {
ws.on('message', function(message) {
console.log('received: %s', message);
try {
console.log('sending: %s', message);
wsReceive.broadcast(message);
} catch (e) {
console.log(e);
}
});
});