Uncaught ReferenceError: io is not defined in flask - javascript

I'm trying to make a chat application with flask and socketio but I get an Uncaught ReferenceError: io is not defined error in my web browsers inspector. Googling this error didn't give me much.
Here is my python code:
import requests
from flask import Flask, jsonify, render_template, request
from flask_socketio import SocketIO, emit
# Configure Flask-socketio
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
#socketio.on('message')
def handleMessage(message):
print('Message: ' + message)
send(message, broadcast=True;)
if __name__ == '__main__':
socketio.run(app)
And here is my html code:
<html>
<head>
<title>Test flask-socketio</title>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
</head>
<body>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', () => {
var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);
//When connected, configure submit button to emit message event
socket.on('connect', () => {
socket.send('User has connected!');
});
});
</script>
<ul id="messages"></ul>
<input type="test" id="myMessage">
<button id="sendbutton">Send</button>
</body>
</html>
Does anybody know why I get this error?

Problem is that you are not getting the socket.io here. Below is correct HTML File code for you
<html>
<head>
<title>Test flask-socketio</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.8/socket.io.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', () => {
var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);
//When connected, configure submit button to emit message event
socket.on('connect', () => {
socket.send('User has connected!');
});
});
</script>
<ul id="messages"></ul>
<input type="test" id="myMessage">
<button id="sendbutton">Send</button>
</body>
</html>
I have updated the Address of Scripts here.
You will be getting cors error next, Goodluck.

Related

How does connect and disconnect work with Sockets

I began learning sockets today and I have some questions about how it works. I'm using flask_socketIO and this is the code I found in a tutorial
Main.py
from flask import Flask
from flask_socketio import SocketIO, send
app = Flask(__name__)
app.config["SECRET_KEY"] = "secret"
socketio = SocketIO(app, cors_allowed_origins="*")
#socketio.on("message")
def handleMessage(msg):
print("Message: " + msg)
send(msg, broadcast=True)
if __name__ == "__main__":
socketio.run(app)
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Chat room</title>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.5.0/socket.io.js"
integrity="sha512-/xb5+PNOA079FJkngKI2jvID5lyiqdHXaUUcfmzE0X0BdpkgzIWHC59LOG90a2jDcOyRsd1luOr24UCCAG8NNw=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(() => {
var socket = io.connect("http://127.0.0.1:5000");
socket.on("connect", () => {
socket.send("User has connected!");
});
socket.once("disconnect", () => {
socket.send("User has disconnected!");
console.log("User Disconnected");
});
socket.on("message", (msg) => {
$("#messages").append("<li>" + msg + "</li>");
console.log("Message recieved");
});
$("#sendButton").on("click", () => {
socket.send($("#myMessage").val());
$("#myMessage").val("");
});
});
</script>
<ul id="messages"></ul>
<input type="text" id="myMessage" />
<button id="sendButton">Send</button>
</body>
</html>
I understand how message works but I don't understand how the connect and disconnect events work. When a new user goes on the page, it logs out both in terminal and on website"User has connected". Why does it do that even though I don't have print() for my terminal or a function similar to
$("#sendButton").on("click", () => {
socket.send($("#myMessage").val());
$("#myMessage").val("");
});
for the website. Also disconnect doesn't work at all, it doesn't console.log when a user disconnects. Does anyone know why?
When a new user goes on the page, it logs out both in terminal and on website"User has connected". Why does it do that even though I don't have print() for my terminal or a function similar to
The browser sends it to the the server. The server prints it (in the server's terminal) and also sends it to all the connected browsers, which log it in #messages.
Also disconnect doesn't work at all, it doesn't console.log when a user disconnects. Does anyone know why?
After the browser disconnects the browser tries to send the message to the server. The server never gets it because the browser already disconnected. Possibly the browser throws an exception when you try to send to a disconnected socket and so it never gets to the next line of code which calls console.log.

Audio streaming with Socket Io

I am working on a project where I can stream audio live to a HTML file from a server, I am using flask_socketio and Socket io for my client side. I am not sure why it is working, here is my code.
server.py
from flask import Flask
from flask_socketio import SocketIO, send
app = Flask(__name__)
app.config['SECRET_KEY'] = 'mysecret'
socketio = SocketIO(app, cors_allowed_origins='*')
with open("bensound-spinningcollins.wav", "rb") as fwav:
data = fwav.read(8)
while data:
data = fwav.read(8)
#socketio.on('message')
def handleMessage(msg):
print('User has connected')
while True:
send(data)
if __name__ == '__main__':
socketio.run(app)
this is my client code
<html>
<head>
<title>Chat Room</title>
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Quicksand&display=swap" rel="stylesheet">
<script src="https://cdn.socket.io/3.1.1/socket.io.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<script type="text/javascript">
var socket = io.connect('http://127.0.0.1:5000');
socket.on('connect', function() {
socket.send('connect');
});
socket.on('message', function(msg) {
audioObj = new Audio(msg);
audioObj.play();
});
</script>
</body>
</html>
Not enough rep to comment, so sorry for the reply.
I think the thing you are actually looking for is WebRTC.
Socket.io is great for sending messages back and forth but not so great at streaming something continuously.
If you try to just play a sound on a message, why not access the audio from JS directly?

GET http://localhost:8563/socket.io/?EIO=3&transport=polling&t=NEsUPis 404 (Not Found)

I've spent days trying to figure out why this is not working, but I didn't get anything out of it.
I tried some other answers about this topic, but none seemed to work for me.
Answers tried:
How to resolve a Socket.io 404 (Not Found) error?
socket.io: Failed to load resource
GET http://localhost:3000/socket.io/socket.io.js 404 (Not Found)
Error: http://localhost:3001/socket.io/ 404 (Not Found)
Socket.io http://localhost:3000/socket.io/socket.io.js 404 (Not Found) - How to configure socket.IO - nodejs, apache2, websockets
Socket.io 404 Not Found
This is my code.
File server.js:
//Dependencies
var express = require('express');
var io = require('socket.io').listen(server);
//Dependencies
//Global variables
var app = express();
var PORT = 3000;
const ROOT = {root : __dirname};
var players = [];
//Global variables
var server = app.listen(PORT, function() {
console.log("Server process started successfully on port " + PORT + "\n");
});
app.get('/', function(req, res) {
console.log("Server called from " + req.socket.remoteAddress + ":" + req.socket.remotePort + "\n");
res.sendFile('html/access.html', ROOT);
});
app.get('/gameSelection', function(req, res) {
let name = req.query.name;
players.push(name);
console.log("New player named " + name + " joined the hub." + "\n");
console.log("Total active players: " + players.length + "\n");
console.log("Complete list of active players: " + players + "\n");
res.sendFile('sketches/menu/index.html', ROOT);
});
app.use(express.static(__dirname + '/sketches/menu'));
io.sockets.on('connection', function(socket){
console.log("We have a new client: " + socket.id);
});
File access.html:
<!DOCTYPE html>
<html>
<head>
<title>Welcome traveler</title>
</head>
<body>
<form method="GET" action="/gameSelection">
Name: <input type="text" name="name" placeholder="Insert your name..." required>
<input type="submit" value="submit">
</form>
</body>
</html>
File menu.js:
const socket = io.connect(window.location.origin);
function setup()
{
createCanvas(600, 400);
ellipse(100, 100, 50, 50);
}
function draw() {}
File index.html:
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script language="javascript" type="text/javascript" src="libraries/p5.min.js"></script>
<script language="javascript" type="text/javascript" src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script language="javascript" type="text/javascript" src="menu.js"></script>
<style> body { padding: 0; margin: 0; } </style>
</head>
<body>
</body>
</html>
As shown by the code, I'm trying to connect via socket.io a p5js page to my node server.
But when I get to the index.html page I get this error:
GET http://localhost:3000/socket.io/?EIO=3&transport=polling&t=NEsXBrx 404 (Not Found)
Request.create # socket.io-1.4.5.js:1
Request # socket.io-1.4.5.js:1
XHR.request # socket.io-1.4.5.js:1
XHR.doPoll # socket.io-1.4.5.js:1
Polling.poll # socket.io-1.4.5.js:1
Polling.doOpen # socket.io-1.4.5.js:1
Transport.open # socket.io-1.4.5.js:1
Socket.open # socket.io-1.4.5.js:1
Socket # socket.io-1.4.5.js:1
Socket # socket.io-1.4.5.js:1
Manager.open.Manager.connect # socket.io-1.4.5.js:2
(anonymous) # socket.io-1.4.5.js:3
I really cannot understand what's wrong with my code, so I hope someone can help.
Thanks in advance.
You are executing this line of code:
var io = require('socket.io').listen(server);
Before server has a value. So, you end up doing this:
var io = require('socket.io').listen(undefined);
Which will probably create a separate web server on a default port which isn't the port you're trying to connect on.
You need to execute this line of code:
var io = require('socket.io').listen(server);
AFTER server already has a value.
Note, if you use const and let and get rid of all occurrences of var, then Javascript would appropriately tell you this was an error because you're attempting to use the variable before it's declaration. That is technically legal with var, but obviously leads to programming mistakes like this. Use let and const instead of var and you can't make this type of mistake nearly as easily.

Is there way to change the value of a variable in a python script from javascript?

I have a python script and apache web server running in a raspberry pi. I want to change the value of a variable in my python script from a web page using javascript. It is possible?
We can use socket. for easily using socket, we can use socket.io
Start.html
<!doctype html>
<html>
<head>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
</head>
<body>
<h1>Socket.IO GPIO control</h1>
<button id="btnGpio">Change GPIO</button>
<script>
var socket = io.connect('http://localhost:5000');
var index = 0;
socket.on('connect', function () {
console.log('connected')
document.getElementById('btnGpio').addEventListener('click', () => {
index = index + 1;
console.log('index', index)
socket.emit('change_gpio', { status: (index % 2 == 0) })
})
});
</script>
</body>
</html>
socket_server.py
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
app = Flask(__name__)
#app.route("/")
def home():
return render_template("Start.html")
socketio = SocketIO(app)
pin = True
#socketio.on('change_gpio')
def handle_my_custom_event(json):
pin = json['status']
print('pin = ' , pin)
#socketio.on('connect', namespace='/')
def test_connect():
print('Connected')
if __name__ == '__main__':
socketio.run(app)
Install library with pip
pip install flask
pip install flask-socketio
Document:
https://flask-socketio.readthedocs.io/en/latest/

Google App Engine channel token is invalid

I'm trying to open a channel by copying and pasting a token into an input box, however the console returns,
Invalid+token.
Here is the code for localhost:8080/
<html>
<head>
<script type="text/javascript" src="https://talkgadget.google.com/talkgadget/channel.js"></script>
<script>
function OpenChannel(){
channel = new goog.appengine.Channel(document.getElementById('Token').value);
socket = channel.open();
socket.onmessage = function(message){
console.log(message);
}
socket.onopen = function(){
connected = true;
console.log('opened');
}
socket.onerror = function(err){
console.log(err.description);
}
socket.onclose = function(){
console.log('closed');
}
}
</script>
</head>
<body>
Token: <input id="Token"></input><br/>
<button onclick="OpenChannel()">Open Channel</button>
</body>
</html>
I'm creating the token by opening, "localhost:8080/token?name=...", which writes the channel token to the page. Here is the python class for that page:
class TokenPage(webapp2.RequestHandler):
def get(self):
token = channel.create_channel(self.request.get('name'))
self.response.write(token)
I've pretty much copied the documentation line for line, so I have no idea whats going wrong.
Solution:
replace
<script type="text/javascript" src="https://talkgadget.google.com/talkgadget/channel.js"></script>
with
<script type="text/javascript" src="/_ah/channel/jsapi"></script>
.
Have you tried:
channel = new goog.appengine.Channel(document.getElementById('Token').value);

Categories

Resources