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
};
Related
I am new to this area so forgive me if I've not explained myself well enough.
I am trying to set up a basic test where the html page that I've made (served using node.js) connects to my javascript template and that sends a string "hello world" to my python program.
I am connecting to port 3000 and using local host. My python module is capable of binding to the port but doesn't print any data that should be sent to the local host.
I am assuming the issue is oriented around the javascript side. Essentially all I am trying to do is have the webserver send the string as soon as the user clicks the button, although I am not sure how to establish this connection between my js template and html template. Even without a button the js fails to send the data.
I did use src = and used "alert("hello")" to check that the two templates were linked, which worked; as soon as the user opened the webpage they got a popup statement. But upon trying to send data using sockets, I'm not sure why no data is being sent from the webpage to my python program.
HTML:
<!DOCTYPE html>
<html>
<body>
<script type = "text/javascript" src = "backendrequest.js"></script>
<input id="clickMe" type="button" value="clickme" onclick="socketPress();" />
</body>
</html>
Javascript:
var net = require('net');
var client = new net.Socket();
client.connect(3000, 'localhost', function() {
console.log('Connected');
client.write('Hello World!');
});
client.on('data', function(data) {
console.log('Received: ' + data);
client.destroy(); // kill client after server's response
});`
Python:
import socket
def Main():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
port = 3000
# connection to hostname on the port.
s.connect((host, port))
# Receive no more than 1024 bytes
msg = s.recv()
s.close()
print (msg.decode('ascii'))
My main objective is to have the user print on python the data, in this case "hello world," coming from my local host, using sockets.
Any advice would be highly appreciated as I just want to know where I am going wrong.
Scenario
C# Based Server
JavaScript Based Client
Situation
I created this fairly simple "server" which only job is to help me understanding how to actually use those websockets in a C# environment.
using (var server = new HttpListener())
{
server.Prefixes.Add("http://localhost:8080/");
server.Start();
while(true)
{
var context = server.GetContext();
if (context.Request.IsWebSocketRequest)
{
var cntxt = context.AcceptWebSocketAsync(null).ConfigureAwait(true).GetAwaiter().GetResult();
var buff = new byte[2048];
while(cntxt.WebSocket.State == System.Net.WebSockets.WebSocketState.Open || cntxt.WebSocket.State == System.Net.WebSockets.WebSocketState.Connecting)
{
cntxt.WebSocket.ReceiveAsync(new ArraySegment<byte>(buff), CancellationToken.None).ConfigureAwait(true).GetAwaiter().GetResult();
Console.WriteLine(Encoding.UTF8.GetString(buff));
}
}
else
{
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
using (var writer = new StreamWriter(context.Response.OutputStream))
{
writer.Write("<html><body>WEBSOCKET ONLY!</body></html>");
}
}
}
}
The problem now is: when i try to add the websocket prefix via server.Prefixes.Add("ws://localhost:8080"), i get some System.ArgumentException thrown which tells my i can only add http and https as accepted protocol.
Thing is: doing it and using ws = new WebSocket('ws://localhost:8080'); (JavaScript) to connect to a websocket, yields for obvious reasons nothing.
Changing the prefix to HTTP in the JS websocket, will provide me with yet another sort-off argument exception.
Actual Question
how to actually get the HttpListener to acceppt web socket requests?
Further Info
Used .net framework is 4.6.1
Browser to test this was Google Chrome 69.0.3497.100
The reason for why the above was not working ... is due to the JS websocket requiring a path.
Changing the above HttpListener prefix to eg. "http://localhost:8080/asdasd/" will allow the socket to connect propertly.
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?
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