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>
Related
I have the following code in file1.html:
<body>
<button type="button" id="accept" value="accept">Accept</button>
<script>
var socket = io.connect('http://localhost:4000');
// Query DOM
var acceptButton=document.getElementById('accept');
// Emit events
acceptButton.addEventListener('click', function(){
socket.emit('notification', {
message: acceptButton.value,
});
});
module.exports=socket;
</script>
</body>
In file2.html:
<body>
<div id="notifications">
<h1>Your notifications here</h1>
</div>
<script>
var socket=require('/file1.html');
var notification=document.getElementById('notifications');
socket.on('notification', function(data){
notification.innerHTML+='<p> the event was accepted<p>';
});
</script>
</body>
Nodejs server code:
var server=app.listen(4000,()=>{
console.log('listening at port 4000');
})
var io=socket(server);
//connection to socket (backend)
io.on('connection',function(socket){
console.log('socket connection made',socket.id);
socket.on('notification', function(data){
console.log(data);
io.sockets.emit('notification', data);
});
});
I am a newbie to socket.io .I want to send the data from file1.html and receive data from file2.html. I don't think there is any mistake in the server code. I am doubtful only in the html files. How do I solve it?
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 have a simple chat application built using sockets,MongoDB,Express.
The application works fine when hosted on my local machine (localhost:4000).
I am able to connect to MongoDB and send and receive messages.
Issue : But when I open the app on my phone browser using the PC IP address (e.g. 192.168.1.108:4000). I can see the index.html page , but unable to send and receive messages and load previous messages from mongodb.
//server.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
connections = [];
app.use(express.static(__dirname + '/public'));
server.listen(process.env.PORT || 4000);
console.log('Server Running');
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
const mongo = require('mongodb').MongoClient;
const client = require('socket.io').listen(server).sockets;
// Connect to mongo
mongo.connect('mongodb://127.0.0.1/mongochat', function(err, db){
if(err){
throw err;
}
console.log('MongoDB connected...');
// Connect to Socket.io
client.on('connection', function(socket){
let chat = db.collection('chats');
// Create function to send status
sendStatus = function(s){
socket.emit('status', s);
}
// Get chats from mongo collection
chat.find().limit(100).sort({_id:1}).toArray(function(err, res){
if(err){
throw err;
}
// Emit the messages
socket.emit('output', res); //whenever we have to pass from server to client(index.html) , we do .emit()
});
// Handle input events
socket.on('input', function(data){
let name = data.name;
let message = data.message;
// Check for name and message
if(name == '' || message == ''){
// Send error status
sendStatus('Please enter a name and message');
} else {
// Insert message
chat.insert({name: name, message: message}, function(){
client.emit('output', [data]);
// Send status object
sendStatus({
message: 'Message sent',
clear: true
});
});
}
});
// Handle clear
socket.on('clear', function(data){
// Remove all chats from collection
chat.remove({}, function(){
// Emit cleared
socket.emit('cleared');
});
});
});
});
<!-- Index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<title>MongoChat</title>
<style>
#messages{height:300px;}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3 col-sm-12">
<h1 class="text-center">
MongoChat
<button id="clear" class="btn btn-danger">Clear</button>
</h1>
<div id="status"></div>
<div id="chat">
<input type="text" id="username" class="form-control" placeholder="Enter name...">
<br>
<div class="card">
<div id="messages" class="card-block">
</div>
</div>
<br>
<textarea id="textarea" class="form-control" placeholder="Enter message..."></textarea>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<script>
(function(){
var element = function(id){
return document.getElementById(id);
}
// Get Elements
var status = element('status');
var messages = element('messages');
var textarea = element('textarea');
var username = element('username');
var clearBtn = element('clear');
// Set default status
var statusDefault = status.textContent;
var setStatus = function(s){
// Set status
status.textContent = s;
if(s !== statusDefault){
var delay = setTimeout(function(){
setStatus(statusDefault);
}, 4000);
}
}
// Connect to socket.io
var socket = io.connect('http://127.0.0.1:4000');
// Check for connection
if(socket !== undefined){
console.log('Connected to socket...');
// Handle Output
socket.on('output', function(data){
//console.log(data);
if(data.length){
for(var x = 0;x < data.length;x++){
// Build out message div
var message = document.createElement('div');
message.setAttribute('class', 'chat-message');
message.textContent = data[x].name+": "+data[x].message;
messages.appendChild(message);
messages.insertBefore(message, messages.firstChild);
}
}
});
// Get Status From Server
socket.on('status', function(data){
// get message status
setStatus((typeof data === 'object')? data.message : data);
// If status is clear, clear text
if(data.clear){
textarea.value = '';
}
});
// Handle Input
textarea.addEventListener('keydown', function(event){
if(event.which === 13 && event.shiftKey == false){
// Emit to server input
socket.emit('input', {
name:username.value,
message:textarea.value
});
event.preventDefault();
}
})
// Handle Chat Clear
clearBtn.addEventListener('click', function(){
socket.emit('clear');
});
// Clear Message
socket.on('cleared', function(){
messages.textContent = '';
});
}
})();
</script>
</body>
</html>
Try binding the http server on 0.0.0.0 through server.listen(process.env.PORT || 4000, '0.0.0.0') and also in your index.html you got
var socket = io.connect('http://127.0.0.1:4000');
which should actually be your internal ip.
I am trying to build a basic chat html program.
I have set up a node server to test it, however, when accessing the html page, I get an socket error. It's my first time working with node.js and setting up node server, so I've surely done something wrong.
Thanks to everyone who's taking a look at this!
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require("socket.io").listen(server);
var socket = io.listen(1223, "1.2.3.4");
server.listen(process.env.PORT || 3000);
console.log('Server is running...');
var people = {};
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
})
// When connecting
socket.on("connection", function(client) {
client.on("join", function(name){
people[client.id] = name;
client.emit("update", "You have connected to the server.");
socket.sockets.emit("update", name + " has joined the server.");
socket.sockets.emit("update-people", people);
});
// When sending
client.on("send", function(msg){
socket.sockets.emit("chat", people[client.id], msg);
});
// When disconnecting
client.on("disconnect", function(){
socket.sockets.emit("update", people[client.id] + " has left the server.");
delete people[client.id];
socket.sockets.emit("update-people", people);
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
</head>
<script>
$(document).ready(function(){
var socket = io.connect("1.2.3.4:1223");
$("#chat").hide();
$("#name").focus();
$("form").submit(function(event){
event.preventDefault();
});
$("#join").click(function(){
var name = $("#name").val();
if (name != "") {
socket.emit("join", name);
$("#login").detach();
$("#chat").show();
$("#msg").focus();
ready = true;
}
});
$("#name").keypress(function(e){
if(e.which == 13) {
var name = $("#name").val();
if (name != "") {
socket.emit("join", name);
ready = true;
$("#login").detach();
$("#chat").show();
$("#msg").focus();
}
}
});
socket.on("update", function(msg) {
if(ready)
$("#msgs").append("" + msg + "");
})
socket.on("update-people", function(people){
if(ready) {
$("#people").empty();
$.each(people, function(clientid, name) {
$('#people').append("" + name + "");
});
}
});
socket.on("chat", function(who, msg){
if(ready) {
$("#msgs").append("" + who + " says: " + msg + "");
}
});
socket.on("disconnect", function(){
$("#msgs").append("The server is not available");
$("#msg").attr("disabled", "disabled");
$("#send").attr("disabled", "disabled");
});
// Sending the message (either by button click or enter)
$("#send").click(function(){
var msg = $("#msg").val();
socket.emit("send", msg);
$("#msg").val("");
});
$("msg").keypress(function(e){
if (e.which == 13) {
var msg = $("msg").val();
socket.emit("send", msg);
$("#msg").val("");
}
});
});
</script>
<body>
<div class="container">
<div class="row">
<div class="span2">
<ul id="people" class="unstyled"></ul>
</div>
<div class="span4">
<ul id="msgs" class="unstyled">
</div>
</div>
<div class="row">
<div class="span5 offset2" id="login">
<form class="form-inline">
<input type="text" class="input-small" placeholder="Your name" id="name">
<input type="button" name="join" id="join" value="Join" class="btn btn-primary">
</form>
</div>
<div class="span5 offset2" id="chat">
<form id="2" class="form-inline">
<input type="text" class="input" placeholder="Your message" id="msg">
<input type="button" name="send" id="send" value="Send" class="btn btn-success">
</form>
</div>
</div>
</div>
</body>
</html>
You mixed up the different listen calls.
var server = require('http').createServer(app);
var io = require("socket.io").listen(server);
var socket = io.listen(1223, "1.2.3.4");
server.listen(process.env.PORT || 3000);
The third line has not the effect you expect. io is not listening itself. It uses the http server that is listening on port 3000.
Rather use this on the server
var server = require('http').createServer(app);
var socket = require("socket.io").listen(server);
server.listen(process.env.PORT || 3000);
And in the client connect to port 3000 (or the port configured via the PORT environment variable.
var socket = io.connect("your.domain:3000");
If you want to listen on a dedicated port for socket.io, you have to create a second http server listening on a second port, and bind that one to socket.io.
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);