Sending string from Javascript to Python code using Sockets - javascript

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.

Related

Receive Strings back from Server to Client using Websockets (Javascript and C++)

I'm new to the subject area so sorry If I've not explained things well.
I created a web API client that sends strings from my HTML (imbedded with JavaScript) back to a node.js server using Web Sockets.
I then swapped out the node.js server with a C++ application that still receives the string data perfectly.
My JS Client(within html script) :
function SendWSData(){
const ws = new WebSocket("ws://localhost:PORT");
ws.addEventListener("open", () => {
console.log("We are connected!");
const stringvalue = `this is a test string`
ws.send(stringvalue);
});
ws.addEventListener("message", ({ data }) => {
console.log(data);
});
}
My C++ Server:
#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
using namespace std;
using tcp = boost::asio::ip::tcp;
string stringVal;
int main() {
auto const address = boost::asio::ip::make_address("IP");
auto const port = static_cast<unsigned short>(std::atoi("PORT"));
boost::asio::io_context ioc{1};
tcp::acceptor acceptor{ioc, {address, port}};
tcp::socket socket{ioc};
acceptor.accept(socket);
std::cout<<"socket accepted"<<std::endl;
std::thread{[q = std::move(socket)]() mutable {
boost::beast::websocket::stream<tcp::socket> ws {std::move(q)};
ws.accept();
while(1)
{
boost::beast::flat_buffer buffer;
ws.read(buffer);
auto out = boost::beast::buffers_to_string(buffer.cdata());
stringVal = out
std::cout<<"stringVal = "<<stringVal<<std::endl;
}
}
This reads data coming into the buffer, and assigns it to a string variable on my C++ app, for me to use.
My question is how would I go about sending back a string to the web page from the C++ app? (especially as my web page is the client and the C++ app is the server)
I know that the server is meant to return a response which is standard, however does that change if I'm trying to implement a function based response? I want to generate a button on the webpage and textbox, and when clicked I get string data from the C++ app.
I've not found much online about sending data from server back to client, as I'm trying to get a request (which is the behaviour of a client). (Could I possibly generate another Web Socket and swap the roles of my web API and C++ app for this particular case; possibly multithreading it?)

Flask's SocketIO isn't sending the right script to my client

I get this warning in Firefox Developer Tools:
The script from “https://js-game-tanks.herokuapp.com/socket.io/socket.io.js” was loaded even though its MIME type (“application/octet-stream”) is not a valid JavaScript MIME type.
and these errors:
SyntaxError: illegal character socket.io.js:1
ReferenceError: io is not defined test:10:20
My thinking is that I should be getting javascript not an octet-stream correct?
My HTML's JavaScript:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
socket.on('any event', function(msg) {
console.log(msg);
});
</script>
Line 10 specifically is var socket = io();.
My Python will detect a connection with:
#socketio.on('connect')
def test_connect():
print('\n\nClient connected\n\n')
emit('we connected', {'data':'woot woot'})
and it will print client connected when I load my page.
And for context, this is deployed via Heroku and I'm using Gunicorn.
How do I resolve this? I am new to Socket.IO, so maybe I am just going about this all wrong.

Socket io - Wrong socket address calling

I have the following code on my static client side:
socket.io.js file calling:
<script src="https://rancher.mysite.com/mymodule/socket.io/socket.io.js"></script>
JS File content:
var socket = io.connect('https://rancher.mysite.com/', {
'path':'/mymodule/socket.io'
});
socket.on('mymodulefunction', function (msg) {
/// Do something (it doesn't call)
});
But socket.io tries to establish the connection with a different address. I can see this on browser developer tools and the address that he is trying to call in "Network" tab is: "https://rancher.mysite.com/socket.io" instead of "https://rancher.mysite.com/mymodule/socket.io".
Please, what am I doing wrong? I'm stuck in this problem for hours...

Javascript Sockets (failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET)

I am trying to create a simple program to send a message to a socket in plain text. The sender is a webpage in javascript using websocket and the server is a C program. I don't have any control over the C code but I have been assured by the codes owners that I can use simple javascript to send the message. My code is as follows:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
//initialize the websocket ws
var ws;
//Open the socket connection
function openSock() {
//test for Websocket compatibility in the browser
if ("WebSocket" in window) {
// log socket attempt
console.log("Attempting to open socket!");
//open web socket ws
ws = new WebSocket("ws://192.168.6.222:11000/echo");
} else { // else the browser doesn't support WebSocket
//Websocket is not supported
alert("APS NOT supported by your Browser!");
}
}
//send the command to socket ws
function sendCommand() {
console.log("Attempting to Send Message");
ws.send("your message here");
}
//close the socket ws
function closeSock() {
console.log("Closing Socket");
// close socket ws
ws.close();
}
</script>
</head>
<body>
<div id="sse">
<input type=submit value="open">
<input type=submit value="send">
<input type=submit value="close">
</div>
</body>
</html>
When I click the connect button I get this error:
WebSocket connection to 'ws://192.168.6.222:11000/echo' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET
I have checked the firewall and the port seems to be open. After spending a fair amount of time troubleshooting the server (making sure it is running and on the network, etc.) I am wondering if I did something wrong with this client side code.
From my limited knowledge and the reading I have done this looks correct but any help is welcome.
This is probably super late but I just ran into a similar problem while using Django channels. I fixed it by adding a slash (/) at the end of the URL.
ws = new WebSocket("ws://192.168.6.222:11000/echo/");
How does the server side of the connection look like?
Maybe you are using a faulty WebSocket Lib which does not provide a valid handshake.
Because when testing the client against ws://echo.websocket.org everything seems to work perfectly fine. This strongly suggests that the websocket client is not source of the problem.
Make sure that your queue is running properly, in my case that was the issue

Client unable to connect to server websocket using gevent-websocket

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
};

Categories