PeerJS peer not receiving data - javascript

I intend to use PeerJs to create P2P connections (data and later video).
I checked the tutorial and used the following code.
In browserA (Chrome 38):
var local;
var remote;
function peerJsInit() {
//listening host
local = new Peer(
{
key: 'myPeerJSKey'
});
local.on('connection', function(conn) {
alert('Connection is open');
conn.on('data', function(data) {
alert('Data: '+data);
});
});
}
function peerSend() {
remote = new Peer(
{
key: 'myPeerJSKey',
debug: true
});
var c = remote.connect('remoteId');
c.on('open', function() {
alert('connected');
c.send(' peer');
});
}
In browserB (Chrome 38):
var local;
var remote;
function peerJsInit() {
//listening host
local = new Peer({
key: 'myPeerJSKey'
});
local.on('connection', function(conn) {
alert('Connection is open');
conn.on('data', function(data) {
alert('Data: '+data);
});
});
}
function peerSend() {
remote = new Peer({
key: 'myPeerJSKey',
debug: true
});
var c = remote.connect('remoteId');
c.on('open', function() {
alert('connected');
c.send(' peer');
});
}
The Connection is open message showed, but the Data and connected messages never.
Can you tell me what I should change?

It seems that I forgot to add another callback.
It is sooo good that JS compiles without a problem, even when callbacks are missing... piece of g*rbage...
So instead of this:
local.on('connection', function(conn) {
alert('Connection is open');
conn.on('data', function(data) {
alert('Data: '+data);
});
});
I have to use this:
local.on('connection', function(conn) {
alert('Connection is open');
conn.on('open',function(){
conn.on('data', function(data) {
alert('Data: '+data);
});
});
});

Related

PeerJS not sending/receiving data

I am currently trying to make a 2 player HTML/JS boardgame and am using PeerJS to connect two players sessions together but cant get it to work.
Here is a quick test i havent been able to get to send/receive data even though connecting works
On the sending end
var peer = new Peer();
var con;
function c() {
con = peer.connect('id');
con.on('error', function(err) { alert(err); });
con.on('data', function(data){ console.log(data) });
};
function send() {
con.on('open', function(){
con.send('HELLO WORLD')
});
}
and on the receiving end:
var peer = new Peer('id');
peer.on('connection', function(con){
console.log('connected')
con.on('error', function(err) { alert(err) });
con.on('open', () => {
con.on('data', (data) => {
console.log('Incoming data', data);
con.send('REPLY');
});
});
});
You need to configure stun and turn servers for Peer. Here is complete working example.
/**********
var peer = new Peer({
config: {
'iceServers': [
{ url: 'stun:stun.l.google.com:19302' },
]
} /* Sample servers, please use appropriate ones */
*******/
<script src="https://unpkg.com/peerjs#1.3.1/dist/peerjs.min.js"></script>
<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 type="text/javascript">
var peer = new Peer({
config: {
'iceServers': [
{ url: 'stun:stun.l.google.com:19302' },
]
} /* Sample servers, please use appropriate ones */
});
peer.on("open", function (id) {
$("#chat").hide()
$("#peerid").text(id)
$("form#connect").submit(function () {
var remoteID = $(this).find('input[type="text"]').val()
console.log("connect to", remoteID);
var conn = peer.connect(remoteID)
gotConnection(conn)
return false;
})
})
peer.on("connection", gotConnection)
function gotConnection(conn) {
conn.on("error", function (err) {
console.error("connection error", err, conn)
})
conn.on("open", function () {
console.log("conn open", conn)
$("#remoteid").text(conn.peer)
$("form#connect").hide()
$("#chat").show()
$("#chat form").submit(function () {
var message = $(this).find('input[type="text"]').val()
console.log("send", message);
conn.send(message)
$(this).find('input[type="text"]').val("")
$("#messages").append($('<li>' + peer.id + ': ' + message + '</li>'))
return false;
})
conn.on("data", function (data) {
console.log("got", data);
$("#messages").append($('<li>' + conn.peer + ': ' + data + '</li>'))
})
})
}
</script>

jquery.js: Uncaught ReferenceError: connect is not defined

I run this code on a website with a database, this interacts with the ambiance.js , jquery.js (3.2.1) and socket.js but I believe this requires some other dependency that I omitted.
var SOCKET = null;
var user = null;
$(document).ready(function() {
connect();
});
function request(msg)
{
var m=msg;
if(m.type == 'aMessage')
{
console.log(m.msg);
}
function connect()
{
if(!SOCKET)
{
var hash = getCookie('hash');
if (hash == '')
{
$.ambiance({message: 'Please login!'});
}
else
{
$.ambiance({message: 'Connecting to server..', type: 'success'});
}
SOCKET = io(':4095');
SOCKET.on('connect', function(msg)
{
if(hash != '')
{
$.ambiance({message: 'Connected', type: 'success'});
}
SOCKET.emit('hash', {
hash: hash
});
});
SOCKET.on('connect_error', function(msg){
$.ambiance({message: 'Connection lost', type: 'error'});
});
SOCKET.on('request', function(msg){
request(msg);
});
}
}
}
Actually, you created the connect() function inside the request function (which wasn't called yet):
Just move it outside and it should work.

Socket.io: emit from client does not work

I'm trying to emit an event on the client, but the server does not respond at all. A message does not appear in the console ('Received!'), the following event is not initiated. The event must emit when the button is clicked. Other actions, such as outputting a message to the console, work fine, but the event does not start. What is the problem? Сonnection events work properly.
Server:
class ChatHandlers {
constructor() {
this.names = {};
this.connection = this.connection.bind(this);
this.send = this.send.bind(this);
this.message = this.message.bind(this);
}
connection(socket) {
socket.emit('new_user', {
name: 'Example name'
});
}
send(socket) {
console.log('Received!');
var ip = socket.handshake.address;
io.sockets.emit('message', {
name: ip,
message: socket.message
});
}
message(socket) {
console.log('Success!');
}
}
var handlers = new ChatHandlers();
io.on('connection', handlers.connection);
io.on('send', handlers.send);
Client:
var socket = io.connect('http://localhost:8080/');
socket.on('connect', function (data) {
socket.on('new_user', function (data) {
console.log(data.name);
});
socket.on('message', function (data) {
console.log(data);
});
$('#send').click(function() {
socket.emit('send', {
message: $('#mess').val()
});
$('#mess').val('');
});

Pusher: Cannot broadcast client event

I'm developing a conference app with laravel 5 and I decide to implement a webRTC solution for that. So, I use Pusher for signaling stuff, but I have a prob: I'm using SimplePeerJs for the webRTC things, when I trigger an event (after subscribing and others stuff), I have the following err:
Pusher : Error : {"type":"WebSocketError","error":{"type":"PusherError","data":{"code":null,"message":"Cannot broadcast client event (connection not subscribed to channel presence-chat)"}}}.
my code is:
Pusher.log = function(message) {
if (window.console && window.console.log)
{
window.console.log(message);
}
};
var currentUser = {
nom: '{{ auth()->user()->first_name }}',
id: {{ auth()->user()->id }},
stream: undefined
};
var pusher = new Pusher('my_app_key', {
authEndpoint: 'pusher/auth',
auth: {
headers: {
'X-CSRF-Token': '{{ csrf_token() }}'
},
params: {
name: currentUser.name,
id: currentUser.id
}
}
});
var channel = pusher.subscribe('presence-chat');
var callback = function() {
console.log('Channel members:', channel.members);
};
//
channel.bind('pusher:subscription_succeeded', callback);
channel.bind('pusher:subscription_error', function(PusherError){
console.log(PusherError);
});
channel.bind('pusher:member_added', function(){
console.log('Member Added');
});
channel.bind('pusher:member_removed', function(){
console.log('Member Removed');
});
//peers stuff
var peer = new SimplePeer({ initiator: true });
peer.on('signal', function (data) {
channel.trigger('client-signal-' + currentUser.id,
{
userId: currentUser.id,
data: data
});
});
peer.on('ready', function () {
peer.send('hey peer, how is it going?')
});
any ideas?
thanks.
The issue is that the Pusher client hasn't had a chance to connect and subscribe to the channel before the peer.on('signal') is being triggered. Did you try moving the peers stuff into the subscription callback ?
var callback = function() {
console.log('Channel members:', channel.members);
//peers stuff
var peer = new SimplePeer({ initiator: true });
peer.on('signal', function (data) {
channel.trigger('client-signal-' + currentUser.id,
{
userId: currentUser.id,
data: data
});
});
peer.on('ready', function () {
peer.send('hey peer, how is it going?')
});
});

socket.io javascript don't work

Anybody an idea why this doesn't work ?
function startServer() {
console.log('function start');
var keyBool = false;
var client = require('socket.io').listen(3000).sockets;
client.on('connection', function (socket) {
console.log('someone connected');
socket.on('party', function (party) {
console.log(party);
console.log('testbla');
});
});
}
the client side:
function client() {
var party = 'test';
var server = "http://127.0.0.1:3000";
try {
var socket = io.connect(server);
} catch (e) {
alert('failed to connect');
}
//setInterval(function () { sendCoordinates }, 125);
//setInterval(function () { sendParty }, 5000);
if (socket !== undefined) {
alert('ok');
try {
socket.emit('party', {
party: 'test'
});
alert('sended...');
} catch (e) {
alert('failed with reason: ' + e);
}
}
}
When I run the server and client logs 'someone connected', but not the party object I send...
Client is an chrome extension and the server a node.js 'file'.
I don't think using some of that code is needed, other than that have you port forwarded?
if (socket !== undefined) {
alert('ok');
try {
Works for me.
$ node server.js
function start
someone connected
{ party: 'test' }
testbla
Maybe you expect the object to be sent before 'ok' is pressed on alert('sended...');..?
alert() is not the best option for debug.
$ node -v
v5.3.0
"socket.io": "^1.3.7"

Categories

Resources