I'm on the socket.io wiki looking into using rooms but join and leave are not working, i'm wondering if they may have changed up a few things but not had the chance to update the wiki?
socket.join("room-"+data.meid);
socket.leave("room-"+meid);
cause im getting console errors:
Uncaught TypeError: Object #<SocketNamespace> has no method 'leave'
Uncaught TypeError: Object #<SocketNamespace> has no method 'join'
It looks like you had the socket.join on the client side. Its a server side function.
Put this on the server:
io.sockets.on('connection', function (socket) {
socket.on('subscribe', function(data) { socket.join(data.room); })
socket.on('unsubscribe', function(data) { socket.leave(data.room); })
});
setInterval(function(){
io.sockets.in('global').emit('roomChanged', { chicken: 'tasty' });
}, 1000);
And this on the client:
var socket = io.connect();
socket.emit("subscribe", { room: "global" });
socket.on("roomChanged", function(data) {
console.log("roomChanged", data);
});
You're probably not declaring 'socket' correctly either that of you haven't installed Socket-io correctly. Try the following...
var io = require("socket.io");
var socket = io.listen(80);
socket.join('room');
socket.leave('room');
There's a useful executable example here.
Related
This is my first webRTC project so I'm very inexperienced in tracing these sorts of errors. Especially since I'm using this NPM package, I don't know exactly what to do with this error message. If you follow that link, I've just copy/pasted the "usage" demo code but replaced some of it with sockets using Laravel echo to transfer the peer-to-peer connection data. In the "usage" demo, they generate an "offer" object and have you paste it into the other peers form. Then that client generates an "answer" object and when you paste it into the form on the initiating client, the connection is made. If I do it that way, everything works fine. But I'm trying to establish an auto-connection when all the clients are ready. Here is my code:
var Peer = require("simple-peer");
window.p = new Peer({
initiator: location.hash === "#1",
trickle: false
});
p.on("error", err => console.log("error", err));
p.on("signal", data => {
if (location.hash === "#1") {
$.ajax({
url: "/autoCon",
type: "get",
data: {
connectionData: JSON.stringify(data)
},
success: function() {
console.log("sent: " + JSON.stringify(data));
}
});
}
});
p.on("connect", () => {
console.log("CONNECT");
});
And then on the blade file, I'm listening with Echo like this:
Echo.channel('myChannel')
.listen('MyEvent', (e) => {
p.signal(e.connectionData)
});
And now for the error:
Failed to execute 'setRemoteDescription' on 'RTCPeerConnection': Failed to set remote offer sdp: Failed to apply the description for 0: Failed to setup RTCP mux.
If I console log p.signal(e.connectionData), it shows "undefined", which is strange because it's generating the "answer" object and displaying to the page in text. So what I've tried to do is ajax send the initial "offer" object to the second peer, then take its "answer" object and signal for the initiating peer to connect when the data is received by socket. But it's giving me that error. Can anyone help?
I ended up figuring this out. This is my final code. It might be messy but it took me like 6 hours into the night and it made my brain hurt XD . If anyone can offer some advice on how to clean it up, I'll gladly take it but this works as is.
in app.js:
p.on("signal", data => {
//document.querySelector("#outgoing").textContent = JSON.stringify(data);
$.ajax({
url: "/autoCon",
type: "get",
data: {
conData: JSON.stringify(data)
}
});
});
And in my blade file using Echo:
var signalData = []
Echo.channel('myChannel')
.listen('MyEvent', (e) => {
signalData.push(e.conData)
if(e.conData.includes('offer') && location.hash !== '#1'){
console.log('received offer')
p.signal(JSON.parse(e.conData))
} else {
if(e.conData.includes('answer') && location.hash === '#1' ){
console.log('received answer')
p.signal(JSON.parse(signalData[1]))
}
}
});
Here is my code:
var socket = require('socket.io-client')('http://127.0.0.1:3000/printers', {
query: "shop=" + "123456",
transports: ["websocket"]
});
If I delete query, I can connect to socket. Where am I wrong?
There doesn't seem to be anything wrong with your client-side code. I can connect by copying and pasting your code.
I suspect the problem is within your server-side code. Here is an example I am using with your client-side code:
var http = require('http');
var io = require('socket.io');
var server = http.createServer(function(req,res){
res.writeHead(200);
res.end('Hello, World!\n');
});
server.listen(80);
var socket = io.listen(server);
socket.use(function(socket, next){
console.log("Query: ", socket.handshake.query);
if (socket.handshake.query.shop == '123456') {
next();
}
next(new Error('You cannot use that shop'));
});
socket.on('connection', function(client) {
console.log('New Connection');
});
I'm able to obtain the query data in the 'socket.use' function. If I don't call the next() function, the client will never get the message that the server has received the response and is connected.
I recommend checking out the example used in this thread.
Error: The connection to <websocket> was interrupted while the page was loading.
Source File: localhost/socket.io/node_modules/socket.io-client/dist/socket.io.js
Line: 2371
I am new to socket.io and I have tried to search for this, but I didn't get an answer.
Websocket is interrupted when I refresh page on Firefox. That's why server side is waiting to authorise client.
Here is code:
server.js
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
fs = require('fs')
app.listen(8080);
function handler(req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.emit('news', {
hello: 'world'
});
socket.on('my other event', function (data) {
//alert(JSON.stringify(data));
console.log(data);
});
});
index.html
<script src="node_modules/socket.io-client/dist/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
socket.on('news', function (data) {
alert(JSON.stringify(data));
console.log(data);
socket.emit('my next event', { my: 'data' });
});
</script>
It happens because, you are not closing your open websocket.
This code would remove this error:
$(window).on('beforeunload', function(){
socket.close();
});
This seems to be an open bug in Firefox (as of 2015-03-29):
https://bugzilla.mozilla.org/show_bug.cgi?id=712329
The workaround (for now) is to call close() on the websocket on beforeunload, as Alexander pointed out.
Update 2016-04: According to Bugzilla, this will be fixed in Firefox 48
I was just running through the Socket.IO tutorials and I ran into this exact problem. I tried the posted solutions but they didn't seem to work at all.
After some fiddling and some screaming and some rubber-ducking, I finally figured out what the issue was. The issue is that it's trying to connect to the socket before the socket variables have been properly initialized. Javascript boo boo #1.
If you will ammend your file to include jQuery and then wrap your functions like so:
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(function(){
var socket = io.connect('http://localhost:8080');
socket.on('news', function (data) {
alert(JSON.stringify(data));
console.log(data);
socket.emit('my next event', { my: 'data' });
});
});
</script>
You will have much more success.
What impact does this have on your application? My guess is that it's just not great to see an error in the console.
The problem here is that you are seeing Firefox loggin this error and there's nothing you can do about it. It's not possible to capture this error with a try...catch block or via websocket.onerror/websocket.onclose.
See: How do I catch a WebSocket connection interruption?
Related:
Should WebSocket.onclose be triggered by user navigation or refresh?
Firefox - Race condition allows ghost WebSocket connections to live after tab closed
I've had this problem with our custom Undertow-based webserver for years -- my problem was that my server was not responding to the socket close message.
Based on a comment by Jan Wielemaker I checked my socket close handler code for AbstractReceiveListener.onFullCloseMessage and realized I had not called the super method. After adding super.close() the socket closes cleanly on the client and no error is emitted.
One solution is to put a timeout on the disconnect event.
setTimeout(() => {
$('#offlineModal').modal('show')
}, 5000)
So i've built a simple websocket client implementation using Haxe NME (HTML5 target ofc).
It connects to
ws://echo.websocket.org (sorry no link, SO sees this as an invalid domain)
which works perfectly!
(i'm using xirsys_stdjs haxelib to use the HTML5 websocket stuff.)
I want to have a local (on my own machine) running websocket server.
I'm using Socket.io at the moment, because i cannot find an easier / simpler solution to go with.
I'm currently trying to use socket.io as socket server, but a 'standard' javascript socket implementation as client (Haxe HTML5), without using the socket.io library clientside.
Does anyone know if this should be possible? because i cannot get it working.
Here's my socket.io code:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(1337);
function handler (req, res) {
fs.readFile(__dirname + '/client.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
// WEBSOCKET IMPLEMENTATION
io.sockets.on('connection', function (socket) {
console.log("webSocket connected...");
socket.on('message', function () {
console.log("server recieved something");
// TODO: find out how to access data recieved.
// probably 'msg' parameter, omitted in example?
});
socket.on('disconnect', function () {
console.log("webSocket disconnected.");
});
});
And here's my Haxe (client) code:
static var webSocketEndPoint:String = "ws://echo.websocket.org";
//static var webSocketEndPoint:String = "ws://localhost:1337";
...
private function initializeWebSocket ():Void {
if (untyped __js__('"MozWebSocket" in window') ) {
websocket = new MozWebSocket(webSocketEndPoint);
trace("websocket endpoint: " + webSocketEndPoint);
} else {
websocket = new WebSocket(webSocketEndPoint);
}
// add websocket JS events
websocket.onopen = function (event:Dynamic):Void {
jeash.Lib.trace("websocket opened...");
websocket.send("hello HaXe WebSocket!");
}
websocket.onerror = function (event:Dynamic):Void {
jeash.Lib.trace("websocket erred... " + event.data);
}
websocket.onmessage = function (event:Dynamic):Void {
jeash.Lib.trace("recieved message: " + event.data);
switchDataRecieved(event.data);
}
websocket.onclose = function (event:Dynamic):Void {
jeash.Lib.trace("websocket closed.");
}
}
In case the Haxe code is unclear: it's using 2 extern classes for the webSocket implementation: MozWebSocket and WebSocket. These are just typed 'interfaces' for the corresponding JavaScript classes.
websocket.io! from the same guys. sample shows exact same thing that you are asking about... and something that I spent past 20 hours searching for (and finally found!)
https://github.com/LearnBoost/websocket.io
Update: Jan 2014
The websocket.io repository has not seen any activity for about 2 years. It could be because it is stable, or it could be because it is abandoned.
The same people have another repository called engine.io. In the readme they say that this is isomorphic with websocket.io... It seems that engine.io is where all the action is these days.
https://github.com/LearnBoost/engine.io
While searching for the same thing I just found https://github.com/einaros/ws/ and its server example worked for me with my pre-existing plain javascript client.
http://socket.io/#how-to-use
At the mentioned link, down towards the bottom of the page,
the socket.io documentation demonstrates as it's last
example, how to use their module as a plain
old xbrowser webSocket server.
SERVER
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket)
{
socket.on('message', function () { });
socket.on('disconnect', function () { });
});
BROWSER
<script>
var socket= io.connect('http://localhost/');
socket.on('connect', function ()
{
socket.send('hi');
socket.on('message', function (msg)
{ // my msg
});
});
</script>
Hope that's what your looking for
--Doc
I am running node v0.5.11 pre
and installed socket.io. I have also install socket.io version 0.9.1
I am running server standard.
var io = require('socket.io').listen(8080);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
which is standard server and following is client ..
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('171.69.117.215:8080');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
when I load client in Firefox using port 80 from server 171.69.117.215 I get in Firebug following error:
io is not defined
[Break On This Error]
var socket = io.connect('171.69.117.215:8080');
I know it is deployment issue as I am loading from port 80 client, which is right way to deploy socket.io application ?
Thanks in advance.
Please insert into client code ..Point to your on node.js server.
<script src="http://yournodeserver/socket.io/socket.io.js"></script>