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.
Related
I am python developer but i need to see my websocket output from browser.
function startSocket() {
var ws = new WebSocket("ws://localhost:8765/")
ws.onopen = function(event) {
ws.send("Sent this from client.js")
console.log(typeof ws.message);
console.log("test")
console.log(ws.message)
}
}
startSocket();
this is my clien.js file.
<!DOCTYPE html><html lang="en">
<head>
<!-- <link rel="stylesheet" type="text/css" href="style.css">-->
<link type="text/css" href="styles.css">
<meta charset="utf-8">
</head>
<body>
<script src="client.js"></script>
</body></html>
and this is my html file.
I am sending a string from my web socket and i want to see inside of a browser.
When i run this html, my web socket is starting to work but my logs are saying undefined.
This is my Log Output
client.js:6 undefined
client.js:7 test
client.js:8 undefined
read more here
bind to the correct event handlers
function startSocket() {
var ws = new WebSocket("ws://localhost:8765/");
ws.onopen = function(event) {
console.log("connection opened");
ws.send("Sent this from client.js")
};
ws.onmessage = function(message) {
console.log(typeof message);
console.log("test")
console.log(message)
};
};
startSocket();
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?
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.
I'm begginer in Node.js or websocket. I have problem:
My HTML code:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script>
"use strict";
var gniazdo = new WebSocket('ws://localhost:3000');
gniazdo.onopen = function(){
console.log('Połączono');
};
gniazdo.onmessage = function(m){
console.log(m.data);
};
</script>
</body>
</html>
My Node.js code:
var io = require('socket.io')(3000);
io.on('connection', function(socket){
console.log('a user connected');
});
I have error in console:
WebSocket connection to 'ws://localhost:3000/' failed: Connection closed before receiving a handshake response
Help plz :)
Your client is using WebSockets, but Socket.IO has its own protocol (that may be transported over WebSockets, but it can also be transported over other protocols). Change your client to use Socket.IO's own client:
<script src="https://cdn.socket.io/socket.io-1.1.0.js"></script>
<script>
'use strict';
var gniazdo = io('ws://localhost:3000');
gniazdo.on('connect', function () {
console.log('Połączono');
gniazdo.on('message', function (m) {
console.log(m.data);
});
});
</script>
I am trying to establish a websocket connection between my signalR server and an android app, built using the phonegap CLI.
The javascript code runs on browsers on my PC but when I package it for android it fails to connect and gives the following error: Error during negotiation request
Here is the javascript code -
<!DOCTYPE html>
<html>
<head>
<title>My New Application</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no;" />
<script type="text/javascript" src="js/jquery-1.7.1.js" ></script>
<script type="text/javascript" src="js/jquery.mobile-1.0.1.js"></script>
<script type="text/javascript" src="js/jquery.signalR-2.0.3.js"></script>
<script type="text/javascript" src="phonegap.js"></script>
<script type="text/javascript" src=http://WEB_ADDRESS.net/signalrPush/signalr/hubs"></script>
<script type="text/javascript">
$(function() {
alert('Phonegap device ready event...');
/*
var connection = $.hubConnection("http://WEB_ADDRESS.net/signalrPush/signalr", { useDefaultPath: false });
connection.error(function (error){
alert("SignalR error: " + error);
});
var pushhubProxy = connection.createHubProxy('pushhub');
pushhubProxy.on('sendmsg',function(message){ $('#ulServerMessages').append('<li>' + message + '</li>'); alert(message);});
connection.start({ transport: ['webSockets', 'longPolling'] }).done(function(){ alert('Now connected, connection ID=' + connection.id);})
.fail(function(){ alert('Could not connect'); });
*/
$.connection.hub.url = "http://WEB_ADDRESS.net/signalrPush/signalr";
var mypushHub = $.connection.pushhub;
if(typeof(mypushHub)=="object")
{
alert(typeof(mypushHub));
mypushHub.client.sendmsg = function (message) {
$('#ulServerMessages').append('<li>' + message + '</li>');
alert(message);
}
$.connection.hub.start({jsonp: true}).done(function () {
mypushHub.server.broadcastmsg();
}).fail(function (error) { alert(error); });
}
else
{
alert(typeof(mypushHub));
alert("Connection Prob");
}
});
</script>
</head>
<body>
<div data-role="header">
<h1>Get Server Data</h1>
</div>
<div id="pusheddata" style="width:300px; height:400px; overflow: auto;">
<ul id="ulServerMessages"></ul>
</div>
</body>
</html>
The asp.net code is hosted on azure.
I also tried to connect without the generated proxy(commented code) which again worked on chrome but not on the android emulator(4.4).
Could someone tell me what I am doing wrong?
Thanks
I am having the same problem as you.
Websocket is a feature within html5 and is not supported by all browsers
Chrome browser supports websockets but android 4.4 (jelly beans) In-browser doesn't.
This is why Android developed kitkat (which supports the websocket).
If you want to use websocket within android 4.2,4.4 (jelly beans), you have to use websocket cordova plugin like the one here
there are alot of others and I am just like you trying to find an answer