I have my browser connecting to system hardware application at localhost using websocket. Sometimes this hardware application disabled, so I want to emulate this hardware application directly in the browser by creating another websocket. How can I do this?
I tried to emulate it by creating two websockets simultaneously, something like this:
socket1 = new WebSocket('ws://localhost:8080')
socket2 = new WebSocket('ws://localhost:8080')
But this doesn't work. How can I establish this connection?
I'd suggest using a mocking framework to mock the server in this situation. I have succesfully used mock-socket to do exactly this, eg. (quoting example from README.md):
var mockServer = new MockServer('ws://localhost:8080');
mockServer.on('connection', function(server) {
server.on('message', function(data) {
server.send('hello world!');
} );
} );
Hope that helps.
Cheers,
Related
I have started an MQTT server just like this example.
This code is hosted in an ASP.Net Core 2.0 application but I have tried console application with no luck.
I have also setup a client using the same demo as above and it connects perfectly. Also an Android client connects fine. But I have placed a MQTT.js client webpage but it will not connect with chrome showing net::ERR_CONNECTION_REFUSED error.
I believe that the problem is with server not supporting web sockets. Because if I start my client with WS type it will not connect.
var options = new MqttClientOptions
{
Server = "localhost",
//ConnectionType = MqttConnectionType.Tcp // Connects
ConnectionType = MqttConnectionType.Ws // Does not connect
};
Now MQTT.js supports TCP as far this link is telling. But I don't seem to be able to work it.
This is the code in my page javascript:
var client = mqtt.connect('tcp://localhost') //Also did mqtt://localhost
client.on('connect', function () {
client.subscribe('myTopic')
client.publish('myTopic', 'Hello mqtt')
})
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
})
I want to know how can I make javascript MQTT client to use TCP? (Any other js plugin maybe?) Or alternatively how can I enable WebSockets in MQTTNet.
Thanks for your help.
MQTT.js does support both native MQTT and MQTT over Websockets, but if you are embedding it in to a web app it can only use MQTT over Websockets because the browsers sandbox will not allow it to use arbitrary TCP connections.
As for enabling Websockets in the broker I can't see anything obvious in the code so you'll probably have to raise and issue against the github project to ask for details.
The next version of MQTTnet (2.5) will have support for WebSocket connections for the server via AspNetCore 2.0.
I need to send data out from my google assistance app to a database. In order to do this, I've created a server that takes the data, packages it, and then sends it out. I have the hostname and port and it works in a normal javascript/node.js program but when I use it in my google assistant app nothing happens. I tried figuring out the problem and it looks like the code just isn't connecting. The code I'm using to send data to the server is as follows:
function sendData(app){
var net = require('net');
var message = {"test": 200};
var thisMessage = JSON.stringify(message);
var client = new net.Socket();
client.connect(<port>, '<hostname>', function() {
app.tell(JSON.stringify(client.address()));
console.log('Connected');
client.write(thisMessage);
});
client.on('data', function(data) {
console.log('Received: ' + data);
client.destroy();
});
client.on('close', function() {
console.log('Connection closed');
});
return 0;
}
(NOTE: Port and hostname left out for privacy purposes)
This completely skips over the app.tell, leading me to believe the connection is never made. I know it works asynchronously with the server, however, I don't understand why it isn't connecting whatsoever.
I have tried it both in simulation and on my smartphone with sandbox on and off. Is there a better way to connect? Note that the server I'm connecting to is python-based.
The problem is likely that you're running it on Cloud Functions for Firebase which has a limit on outbound connections under their free "Spark" plan. With this plan, you can only connect to other Google services. This is usually a good way to start understanding how to handle Action requests, but has limitations. To access endpoints outside of Google, you need to upgrade to either their "Flame" fixed price plan or "Blaze" pay-as-you-go plan.
You do not, however, need to run on Google's servers or need to use node.js. All you need is a public HTTPS server with a valid SSL cert. If you are familiar with JSON, you can use any programming language to handle the request and response. If you are familiar with node.js, you just need a node.js server that can create Express request and response objects.
I've a client to server Websocket connection which should be there for 40 seconds or so. Ideally it should be forever open.
The client continually sends data to server and vice-versa.
Right now I'm using this sequence:
var socket;
function senddata(data)
{
if (!socket)
{
socket = new WebSocket(url);
socket.onopen = function (evt) {
socket.send(data);
socket.onmessage = function (evt) {
var obj = JSON.parse(evt.data);
port.postMessage(obj);
}
socket.oneerror = function (evt) {
socket.close();
socket = null;
}
socket.onclose = function(evt){
socket = null;
}
}
}
else
{
socket.send(data);
}
}
Clearly as per current logic, in case of error, the current request data may not be sent at all.
To be frank it sometimes gives error that websocket is still in connecting state. This connection breaks often due to networking issues. In short it does not work perfectly well.
I've read a better design : How to wait for a WebSocket's readyState to change but does not cover all cases I need to handle.
Also I've Googled about this but could not get the correct procedure for this.
So what is the right way to send regular data through Websockets which handles well these issues like connection break etc?
An event you don't seem to cover is onclose. Which should work really well, since it's called whenever the connection terminates. This is more reliable than onerror, because not all connection disruptions result in an error.
I personally use Socket.IO, it enables real-time bidirectional event-based communication between client and server.
It is event driven. Events such as
on connection :: socket.on('conection',callback);
and
on disconnect :: socket.on('disconnect',callback);
are built in with socket.io so it can help you with your connection concerns. Pretty much very easy to use, check out their site if you are interested.
I use two-layer scheme on client: abstract-wrapper + websocket-client:
The responsibilities of the websocket-client are interacting with a server, recovering the connection and providing interfaces (event-emitter and some methods) to abstract-wrapper.
The abstract-wrapper is a high-level layer, which interacts with websocket-client, subscribes to its events and aggregating data, when the connection is temporary failed. The abstract-wrapper can provide to application layer any interface such as Promise, EventEmitter and so on.
On application layer, I just work with abstract-wrapper and don't worry about connection or data losing. Undoubtedly, it's a good idea to have here information about the status of connection and data sending confirmation, because it's useful.
If it is necessary, I can provide some code for example
This apparently is a server issue not a problem in the client.
I don't know how the server looks like here. But this was a huge problem for me in the past when I was working on a websocket based project. The connection would continuously break.
So I created a websocket server in java, and that resolved my problem.
websockets depend on lots of settings, like if you're using servlets then servlet container's settings matter, if you're using some php etc, apache and php settings matter, for example if you create a websocket server in php and php has default time-out of 30 seconds, it will break after 30 seconds. If keep-alive is not set, the connection wont stay alive etc.
What you can do as quick solution is
keep sending pings to a server after a certain amount of time (like 2 or 3 seconds, so that if a websocket is disconnected it is known to the client so it could invoke onclose or ondisconnect, I hope you know that there is no way to find if a connection is broken other than failing to send something.
check server's keep-alive header
If you have access to server, then it's timeouts etc.
I think that would help
My goal is to implement a websocket client in JavaScript with specific protocol.
This client should be platform independent. It should be able to run from NodeJS environment and from browsers as well. I know that one option is to use browserify on NodeJS packages and than use the result in browser, but I wonder if there is other more elegant sollution?
Also at the github repo of ws NodeJS package that is the most popular I think is being said that it returns global.WebSocket which has slightly different API.
Can I still use it for platform independent client application?
Thanks for any reply.
In the end I used https://websockets.github.io/ws/ package for NodeJS which is compatible with browser WebSocket protocol API.
var WebSock = global.WebSocket || global.MozWebSocket || require('ws');
this.sock = new WebSock(url, this.subProtocol);
this.sock.onopen = (evt) => {};
this.sock.onmessage = (msg) => {};
this.sock.onerror = (err) => {};
Depending on your specific requirements I have found Socket.io to work well for both NodeJS (using socket.io-client and browser. It does more then just WebSockets though so make sure and look into it more as it may not suit your specific purposes.
I am using it for a task queue and have been pleased with it.
Take a look at sockjs for SockJS-client as a JavaScript client library and
SockJS-node for the server implementation.
http://sockjs.org
I'm trying to use WebSockets in PHP and Javascript and I'm confused, it uses the protocol ws:// and wss:// and the server (hostgator) not enabled these protocols (I think!) And I can not connect, someone know if I need to enable these protocols on the server or how do I connect?
EDIT: It is possible to use websockets for streaming audio?
I tried connecting to another server I found in examples and got ...
Following code:
<script>
var connection = new WebSocket('ws://echo.websocket.org/')
connection.onopen = function(e) {
alert("Connected");
console.log("Connected");
};
connection.onclose = function(e) {
alert("Connection closed");
console.log("Connection closed");
};
</script>
I think this might help.
This is the programming assignment I made on PHP. Its a 2-way chat application which deploys a Client-Server on both the machines.
Client A talks to Server B
Client B talks to Server A
http://rishabhmehan.com/?attachment_id=255
This will be good for reference. It has the readme file in it, that can help you.
Also check this - http://www.codeproject.com/Tips/418814/Socket-Programming-in-PHP