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);
Related
I saw this js code online and i modified the best my knowledge to make it not only visible to current user but all users:
var textarea = $('#textarea');
var typingStatus = document.querySelector('#typing_on');
var lastTypedTime = new Date(0); // it's 01/01/1970
var typingDelayMillis = 2000; // how long user can "think about his spelling" before we show "No one is typing -blank space." message
function refreshTypingStatus() {
if (!textarea.is(':focus') || textarea.val() == '' || new Date().getTime() - lastTypedTime.getTime() > typingDelayMillis) {
socket.emit('stat', typingStatus.innerHTML = 'no type');
} else {
socket.emit('stat', typingStatus.innerHTML = 'User typing....');
}
}
function updateLastTypedTime() {
lastTypedTime = new Date();
}
setInterval(refreshTypingStatus, 100);
textarea.keypress(updateLastTypedTime);
textarea.blur(refreshTypingStatus);
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<link rel="stylesheet" type="text/css" href="styles2.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<input name="textarea" id="textarea" cols="45" rows="5">
<div id="typing_on"></div>
</body>
What i did in front end is add socket.emit to the result as seen above and i did equivalent to that in back-end (server.js)
but it doens't work and show like this:
what i want is for the 'user typing' to appear in both sides (clients)
How can i do that?
To send message from client to server and then sending the message to all clients connected to the websocket:
server.js
io.on('connect', socket => {
let counter = 0;
setInterval(() => {
socket.emit('hello', ++counter);
}, 1000);
});
Index.html
const socket = io();
socket.on('connect', () => {
$events.appendChild(newItem('connect'));
});
socket.on('hello', (counter) => {
$events.appendChild(newItem(`hello - ${counter}`));
});
If you want to send message to all clients except the person who is sending the message, use broadcast instead of emit
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 need to connect HTML website to node server chat application. HTML client side has some HTML files and javascript file.I need to connect socket.io chat server using javascript. So it needs to initialize socket.io port inside javascript.
I have created socket.io chat server in node.js using javascript it is working fine. And I need to call that node server using javascript client site.
It should initialize and socket server connect. It should able to emit and receive messages from the server site.
I have a socket.io backend service which is working fine. Because I test it with nodeJS client application. But I need it to use existing HTML web site which is not nodeJS
I have searched on google and can't find any website which is about connecting sockt.io using a javascript file. All tutorials are using nodeJS.
When I used
var io = require('socket.io').listen(server);
inside the javascript file and open HTML page in the browser, it throws an error.
This is my code, I got this from the internet I was trying to connect this implement my real code.
<!DOCTYPE html>
<html>
<head>
<link href="style.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
// socket.io specific code
var socket = io.connect('http://localhost:8000');
socket.on('connect', function () {
$('#chat').addClass('connected');
});
socket.on('announcement', function (msg) {
$('#lines').append($('<p>').append($('<em>').text(msg)));
});
socket.on('nicknames', function (nicknames) {
$('#nicknames').empty().append($('<span>Online: </span>'));
for (var i in nicknames) {
$('#nicknames').append($('<b>').text(nicknames[i]));
}
});
socket.on('user message', message);
socket.on('reconnect', function () {
$('#lines').remove();
message('System', 'Reconnected to the server');
});
socket.on('reconnecting', function () {
message('System', 'Attempting to re-connect to the server');
});
socket.on('error', function (e) {
message('System', e ? e : 'A unknown error occurred');
});
function message(from, msg) {
$('#lines').append($('<p>').append($('<b>').text(from), msg));
}
// dom manipulation
$(function () {
$('#set-nickname').submit(function (ev) {
socket.emit('nickname', $('#nick').val(), function (set) {
if (!set) {
clear();
return $('#chat').addClass('nickname-set');
}
$('#nickname-err').css('visibility', 'visible');
});
return false;
});
$('#send-message').submit(function () {
message('me', $('#message').val());
socket.emit('user message', $('#message').val());
clear();
$('#lines').get(0).scrollTop = 10000000;
return false;
});
function clear() {
$('#message').val('').focus();
};
});
</script>
</head>
<body>
<div id="chat">
<div id="nickname">
<form id="set-nickname" class="wrap">
<p>Please type in your nickname and press enter.</p>
<input id="nick">
<p id="nickname-err">Nickname already in use</p>
</form>
</div>
<div id="connecting">
<div class="wrap">Connecting to socket.io server</div>
</div>
<div id="messages">
<div id="nicknames"></div>
<div id="lines"></div>
</div>
<form id="send-message">
<input id="message">
<button>Send</button>
</form>
</div>
</body>
</html>
Error in the front end:
Uncaught ReferenceError: io is not defined
at chat-footer.html:10
This is my folder structure:
var io = require('socket.io').listen(server); should be on the server side. var socket=io(); should be in the client side javascript. If you are putting var io in the client side then you would get an error. Plus you need to link the socket io library in the <head> tag of the HTML: <script src='/socket.io/socket.io.js'></script>. If you do not have the library linked the io() function will not work. I hope that this solves your problem.
UPDATED
According to your code. You never defined the io(); function. You went ahead in the front end and said var socket = io.connect(). You never said what io is. What it should be is name a different variable var socket = io(); and then use var connector = io.connect().
SECOND UPDATE
If the html page is not being served from the nodejs backend, you will not be able to use socketio as it is not connected to a server. You need to serve the html page from the backend and use socketio on the same backend server.
I have resolved the error. The reason was I cannot add a socket.io reference directly because it's nodeJS script. So I added socket.io.js from nodeJS service library. By adding that my HTML page will directly refer running nodeJS server socket.io.js file.
This is my working and complete code to connect socket.io nodeJS server.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script src="http://localhost:8000/socket.io/socket.io.js"></script> // add this line
<script>
var socket = io.connect('http://localhost:8000');
socket.on('connect', function () {
$('#chat').addClass('connected');
});
socket.on('announcement', function (msg) {
$('#lines').append($('<p>').append($('<em>').text(msg)));
});
socket.on('nicknames', function (nicknames) {
$('#nicknames').empty().append($('<span>Online: </span>'));
for (var i in nicknames) {
$('#nicknames').append($('<b>').text(nicknames[i]));
}
});
socket.on('user message', message);
socket.on('reconnect', function () {
$('#lines').remove();
message('System', 'Reconnected to the server');
});
socket.on('reconnecting', function () {
message('System', 'Attempting to re-connect to the server');
});
socket.on('error', function (e) {
message('System', e ? e : 'A unknown error occurred');
});
function message(from, msg) {
$('#lines').append($('<p>').append($('<b>').text(from), msg));
}
// dom manipulation
$(function () {
$('#set-nickname').submit(function (ev) {
socket.emit('nickname', $('#nick').val(), function (set) {
if (!set) {
clear();
return $('#chat').addClass('nickname-set');
}
$('#nickname-err').css('visibility', 'visible');
});
return false;
});
$('#send-message').submit(function () {
message('me', $('#message').val());
socket.emit('user message', $('#message').val());
clear();
$('#lines').get(0).scrollTop = 10000000;
return false;
});
function clear() {
$('#message').val('').focus();
};
});
</script>
</head>
<body>
<div id="chat">
<div id="nickname">
<form id="set-nickname" class="wrap">
<p>Please type in your nickname and press enter.</p>
<input id="nick">
<p id="nickname-err">Nickname already in use</p>
</form>
</div>
<div id="connecting">
<div class="wrap">Connecting to socket.io server</div>
</div>
<div id="messages">
<div id="nicknames"></div>
<div id="lines"></div>
</div>
<form id="send-message">
<input id="message">
<button>Send</button>
</form>
</div>
</body>
</html>
I've been trying to get two browsers communicate with each other using PeerJS, however am unable to overcome this hurdle.
As far as I can tell, the chrome console indicates that a successful connection has been established between the two browsers, however I cannot get either client to receive any data.
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<script src="http://cdn.peerjs.com/0.3/peer.min.js"></script>
<script src="peer.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<label id="yourID">Your ID is: </label><br>
<label id="currentConn">You are currently connected to: </label>
<div>
<button id="connectButton">Connect to this ID</button>
<input type="text" id="toConnectID">
</div>
<hr>
<div>
<textarea id="playArea"></textarea><br>
<button id="sendMessage">Send Message</button>
</div>
<script>
console.log("JS Started");
var peer1 = new Peer({key: 'lwjd5qra8257b9', debug: 3});
document.getElementById("connectButton").disabled = true;
document.getElementById("sendMessage").disabled = true;
peer1.on('open', function(id){
console.log("Peer1 ready");
document.getElementById("connectButton").disabled = false;
document.getElementById("yourID").innerHTML = "Your ID is: "+id;
peer1.on('data', function(data){
console.log("Data received: "+data);
document.getElementById("playArea").value = data;
});
});
peer1.on('connection', function(dataConnection){
document.getElementById("sendMessage").disabled = false;
document.getElementById("currentConn").innerHTML = "You are currently connected to: "+dataConnection.peer;
conn = dataConnection;
});
$("#connectButton").click(function(){
ID = document.getElementById("toConnectID").value;
conn = peer1.connect(ID);
document.getElementById("currentConn").innerHTML = "You are currently connected to: "+ID;
document.getElementById("sendMessage").disabled = false;
});
$("#sendMessage").click(function(){
text = document.getElementById("playArea").value;
conn.send(text);
console.log("Data sent: "+text);
});
</script>
</body>
</html>
The end goal is to have the browsers communicate over a local network, so code is purely to test the PeerJS library.
Any help would be much appreciated.
your on('data') subscriber should be under conn.on('data') instead of peer1.on('data') .
and you need conn.on('data') in 2 places to be able to receive data in both end. One for the client who establish connection itself, under conn.on('data'), one for the client who got connected, under peer1.on('connection'). If you remove any1 of them, you will see only one end is receiving data.
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<script src="http://cdn.peerjs.com/0.3/peer.min.js"></script>
<script src="peer.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<label id="yourID">Your ID is: </label><br>
<label id="currentConn">You are currently connected to: </label>
<div>
<button id="connectButton">Connect to this ID</button>
<input type="text" id="toConnectID">
</div>
<hr>
<div>
<textarea id="playArea"></textarea><br>
<button id="sendMessage">Send Message</button>
</div>
<script>
console.log("JS Started");
var peer1 = new Peer({key: 'lwjd5qra8257b9', debug: 3});
document.getElementById("connectButton").disabled = true;
document.getElementById("sendMessage").disabled = true;
var conn;
peer1.on('open', function(id){
console.log("Peer1 ready");
document.getElementById("connectButton").disabled = false;
document.getElementById("yourID").innerHTML = "Your ID is: "+id;
});
peer1.on('connection', function(dataConnection){
document.getElementById("sendMessage").disabled = false;
document.getElementById("currentConn").innerHTML = "You are currently connected to: "+dataConnection.peer;
conn = dataConnection;
conn.on('data', function(data){
console.log("Data received: "+data);
document.getElementById("playArea").value = data;
});
console.log("Connected")
});
$("#connectButton").click(function(){
ID = document.getElementById("toConnectID").value;
conn = peer1.connect(ID);
conn.on('open',function(){
console.log("open")
conn.on('data', function(data){
console.log("Data received: "+data);
document.getElementById("playArea").value = data;
});
})
document.getElementById("currentConn").innerHTML = "You are currently connected to: "+ID;
document.getElementById("sendMessage").disabled = false;
});
$("#sendMessage").click(function(){
text = document.getElementById("playArea").value;
conn.send(text);
console.log("Data sent: "+text);
});
</script>
</body>
</html>
I have the following code below :
<!DOCTYPE html>
<html>
<head>
<script src="http://connect.soundcloud.com/sdk.js"></script>
<script>
SC.initialize({
client_id: "f520d2d8f80c87079a0dc7d90db9afa9"
});
SC.get("/users/3207",{}, function(user){
console.log("in the function w/ " + user);
});
</script>
</head>
</html>
The code should print the user name to the console however whenever I run this, my console gives the error of :
Failed to load resource: The requested URL was not found on this server:
file://api.soundcloud.com/users/3207?client_id=f520d2d8f80c87079a0dc7d90db9afa9&format=json&_status_code_map%5B302%5D=200
However if I were to directly http://api.soundcloud.com/users/3207.json?client_id=f520d2d8f80c87079a0dc7d90db9afa9, then I get a valid JSON result.
Is there something incorrect with my how I am using the SC.get function?
Thanks
Well, you should test your index.html locally on a web-server like Apache and not by opening it as a file.
Working example
SC.initialize({
client_id: "f520d2d8f80c87079a0dc7d90db9afa9"
});
SC.get("/users/3207", {}, function(user) {
console.log("in the function w/ " + JSON.stringify(user));
var res = document.getElementById("result");
res.innerHTML = JSON.stringify(user);
});
<script src="http://connect.soundcloud.com/sdk.js"></script>
<div id="result"></div>