Hey there I have a huge issue. I created a web socket system using the Ratchet framework for pho. It works perfectly fine on my local server but for some reason it won't work on my live server. My server is on digital ocean so I'm pretty familiar with the server. I use Apache also. But this is how my we sockets JavaScript code look right now for connecting:
if(typeof(WebSocket) == "function")
{
var host = "wss://www.frindse.com:8181/?chathash=" + mainChatId;
var conn = new WebSocket(host);
conn.onopen = function(e) {
console.log("Connection established!");
// Send back the chat id
conn.send(JSON.stringify({event: "supplyChatHash", data: mainChatId}));
// Add this new user to the connection
conn.send(JSON.stringify({event: "connectNewUserToChat", data: {userId: logged, connectedTo: mainChatId}}));
};
conn.onclose = function(e) {
alert('Disconnected');
};
}
And here is the code for starting the server:
$server = IoServer::factory(
new HttpServer(
new WsServer(
new ChatServerBackend($_GET['chathash'])
)
),
8181
);
For some reason my we sockets server won't start on my live site. Does it have to do with a port? Or anything else?
Related
i have a docker compose that contains 3 containers " node-red , influxdb , a html with JavaScript webpage with nginx:alpine image "
in the html and JavaScript webpage i have a list of images and i change the image according to the data that come from node red via websockets
and i receive my data with this JavaScript function
function startConnect() {
document.getElementById('dt').click();
socket = new WebSocket("ws://mywebsite.com:1880/ws/test");
socket.onmessage = function(e) {onMessageArrived(e.data)}
console.log("connected");
socket.onopen = function() {socket.send("1")};
}
// Called when a message arrives
function onMessageArrived(message) {
console.log("onMessageArrived: " + message);
var obj = JSON.parse(message);
document.getElementById("image1").src = "myimage/" + obj.L + "_DL.png";
document.getElementById("image2").src = "myimage/" + obj.M + obj.F + obj.S + "_" + obj.Z48_70 + "_M.png";
document.getElementById("image3").src = "myimage"+ obj.V + obj.V + "_X";
}
every thing worked fine until i have decided to use docker for "node-red and influx and the html webpage" and use nginxwithout docker with letsencrypt certifacts to handle the reverse proxy of my 3 containers.
The problem that i am facing is that i cannot receive data with websockets even though i change the socket = new WebSocket("ws://mywebsite.com:1880/ws/test") to socket = new WebSocket("ws://mywebsite.com:6100/ws/test") the port 6100 used by my webpage contain with this i am having an https error and with socket = new WebSocket("ws://192.170.0.6:6100/ws/test") the IP address of my webpage container and also with new WebSocket("ws://mywebsite/webpage/ws/test") this is handeled by nginx to route it the IP and the port used by my webpage container
If you are connecting to a WebSocket address that is being boot strapped via HTTPS then you need to use the wss: scheme rather than ws:
So if you have enabled https on port 6100 then you need to use wss://mywebsite.com:6100/ws/test
(also if you are using nginx as a reverse proxy is there any reason not to use the default ports of 80 and 443 for http/https respectively?)
EDIT:
If your proxy is presenting the default ports of 80/443 for http/https respectively then you should be using something like the following:
function startConnect() {
document.getElementById('dt').click();
if (location.scheme === 'http:' ) {
socket = new WebSocket("ws://mywebsite.com/ws/test");
} else {
socket = new WebSocket("wss://mywebsite.com/ws/test");
}
socket.onmessage = function(e) {onMessageArrived(e.data)}
console.log("connected");
socket.onopen = function() {socket.send("1")};
}
This will pick ws:// or wss:// depending on how the page is loaded (http vs https)
I am using hapijs in my MEAN stack and implemented socket.io (using this for reference: http://matt-harrison.com/using-hapi-js-with-socket-io/) Everything works fine, no problems there. It works great in my application!
However, there will be script I will be running via command line separately (which will be doing some maintenance on the application) that I was hoping to connect to the same web socket and be able to push to clients messages if data needs to be refreshed.
My index.js taken straight from the example:
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 3000 });
var io = require('socket.io')(server.listener);
io.on('connection', function (socket) {
socket.emit('Hello');
});
server.start();
I tried to create a separate JS file, and do a:
var socket = require('socket.io');
var io = socket.listen(3000);
Then passed io to send a message. This doesn't seem right... I guess I'm wondering if this can even be done. Messing around I've either created a separate web socket or no connection to the client.
Please let me know if I need to provide more information.
Thanks.
T
In your provided code, you're creating 2 servers. [io.listen()][1] listens on a port as a server.
What you need to do instead to pass messages around is to create a socket.io client in your separate script. There's a separate module for this called socket.io-client, which you can require to be a client:
client.js
var io = require('socket.io-client');
var socket = io('http://localhost:3000');
socket.on('beep', function () {
console.log('beep');
socket.emit('boop');
});
server.js
Here's a slightly updated version of your server script too (hapi v9.0.0 has a mandatory callback for server.start()):
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 3000 });
var io = require('socket.io')(server.listener);
io.on('connection', function (socket) {
socket.emit('beep');
socket.on('boop', function () {
console.log('boop');
});
});
server.start(function () {
console.log('Started Server!');
});
If you open up a couple of terminals and run these, you should see messages passed between them and beep and boop logged out:
I am trying to stream data from a background server application to a client-side web-page using gevent-websocket.
When using localhost or leaving ('',8999) I am able to connect to the web-socket, but when trying to access from off the server I cannot seem to connect with the error 'Firefox can't establish a connection to the server at ws://SERVER-IP:8999/.'
I have tried other browsers with the same issue (well I tried chrome as well)
def app(environ, start_response):
ws = environ['wsgi.websocket']
stream_listener.add_socket(ws)
while not ws.closed:
gevent.sleep(0.1)
server = pywsgi.WSGIServer(
('0.0.0.0', 8999), app, handler_class=WebSocketHandler)
server.serve_forever()
As I said I have tried leaving it blank - putting in '0.0.0.0' in hopes that would bind it to all interfaces, but still no luck.
Here is the client side script that works from localhost - but trying to put in the SERVER-IP:8999 fails.
var ws = new WebSocket("ws://SERVER-IP:8999/");
ws.onopen = function() {
ws.send("Hello, world")
}, ws.onmessage = function(a) {
var b = JSON.parse(a.data);
//do something with b
};
I am working on a node.js application that will connect to a UNIX socket (on a Linux machine) and facilitate communication between a web page and that socket. So far, I have been able to create socket and communicate back and forth with this code in my main app.js:
var net = require('net');
var fs = require('fs');
var socketPath = '/tmp/mysocket';
fs.stat(socketPath, function(err) {
if (!err) fs.unlinkSync(socketPath);
var unixServer = net.createServer(function(localSerialConnection) {
localSerialConnection.on('data', function(data) {
// data is a buffer from the socket
});
// write to socket with localSerialConnection.write()
});
unixServer.listen(socketPath);
});
This code causes node.js to create a UNIX socket at /tmp/mysocket and I am getting good communication by testing with nc -U /tmp/mysocket on the command line. However...
I want to establish a connection to an already existing UNIX socket from my node.js application. With my current code, if I create a socket from the command line (nc -Ul /tmp/mysocket), then run my node.js application, there is no communication between the socket and my application (The 'connect' event is not fired from node.js server object).
Any tips on how to go about accomplishing this? My experiments with node.js function net.createSocket instead of net.createServer have so far failed and I'm not sure if that's even the right track.
The method you're looking for is net.createConnection(path):
var client = net.createConnection("/tmp/mysocket");
client.on("connect", function() {
... do something when you connect ...
});
client.on("data", function(data) {
... do stuff with the data ...
});
I was just trying to get this to work with Linux's abstract sockets and found them to be incompatible with node's net library. Instead, the following code can be used with the abstract-socket library:
const abstract_socket = require('abstract-socket');
let client = abstract_socket.connect('\0my_abstract_socket');
client.on("connect", function() {
... do something when you connect ...
});
client.on("data", function(data) {
... do stuff with the data ...
});
You can also connect to a socket like this:
http://unix:/path/to/my.sock:
I am using the python tornado framework to write a small web server for a game I'm writing. The get requests are working fine however, when I try to create a websocket connection I get this error in my browser:
Here is my javascript code:
var ws = new WebSocket("ws://localhost:8888/ws");
ws.onopen = function() {
ws.send("ping");
};
Here is the code for the python server:
class StateQueryHandler(tornado.websocket.WebSocketHandler):
def open(self):
state.players = state.players + 1
self.write(state.players)
print("socket opened")
. . .
application = tornado.web.Application([
(r"/ws", StateQueryHandler),#websocket endpoint
(r"/static/(.*)", tornado.web.StaticFileHandler, {"path": "../client"})
])
server = tornado.httpserver.HTTPServer(application)
server.listen(8888)
tornado.ioloop.PeriodicCallback(state.update, 250).start()
tornado.ioloop.IOLoop.instance().start()
Can anyone tell me what is going wrong? Do I have to do anything extra on the server side to keep the tcp connection alive ?
Try this:
class StateQueryHandler(tornado.websocket.WebSocketHandler):
def open(self):
state.players = state.players + 1
self.write_message(state.players)
print("socket opened")
You need to call the method write_message, not write.
Check out the documentation for more info: http://www.tornadoweb.org/en/branch2.4/websocket.html