I am trying to use socket.io with pubnub. I am not able to understand how to get data on client(index.html) which I have published on the server.Below is the sample code.
my server.js
var pubnub = require("pubnub")
var p = pubnub.init({
"subscribe_key" : "xxxx",
"publish_key" : "xxxx",
"params" : {},
});
p.publish({
"message" : "foo",
"channel" : "test_channel",
});
client code - index.html
<script src="http://cdn.pubnub.com/socket.io.min.js"></script>
<script>(function(){
// IMPORTANT: PubNub Setup with Account
var pubnub_setup = {
channel : 'test_channel',
publish_key : 'xxxx',
subscribe_key : 'xxxx'
};
var socket = io.connect( 'http://pubsub.pubnub.com/', pubnub_setup );
socket.on( 'connect', function() {
console.log('Connection Established! Ready to send/receive data!');
} );
socket.on( 'message', function(message) {
console.log(message);
} );
socket.on( 'disconnect', function() {
console.log('my connection dropped');
} );
socket.on( 'reconnect', function() {
console.log('my connection has been restored!');
} );
})();</script>
PubNub Socket.io SDK
As stated in this other Stack Overflow thread, the PubNub Socket.IO SDK for PubNub is designed for people that started with socket.io but want to migrate to PubNub. Otherwise, there is no requirement to use Socket.IO SDK if you are starting with PubNub first and you should use the latest PubNub Node SDK and PubNub JavaScript SDK or whatever PubNub SDK you require.
And the newly implemented, ES5 compliant PubNub JavaScript/Node v4 SDKs (currently in beta) are coming soon!
Related
I copied the client socket.io script from the cdn and then used importScript but when i tru to run it gives
ReferenceError: document is not defined
at JSONPPolling.doPoll (socketio.js:3683)
at JSONPPolling.poll (socketio.js:4369)
at JSONPPolling.doOpen (socketio.js:4313)
at JSONPPolling.open (socketio.js:3399)
at Socket.open (socketio.js:2796)
at new Socket (socketio.js:2725)
at socketio.js:2560
at Manager.open (socketio.js:470)
at new Manager (socketio.js:383)
at lookup (socketio.js:220)
How can i solve this, my code for the service worker file is
try {
importScripts('socket/socketio.js')
const socket = io("http://localhost:8080")
socket.on('connect', () => {
console.log(socket.id)
})
} catch (e) {
console.log(e)
}
For me {jsonp: false} did omit the document error, but didn't get connected to my server.
try using { transports: ['websocket'] } as options in socket.io connection
service_worker.js
const socket = io('http://localhost:9000', { transports: ['websocket'] });
In my node server
const io = require('socket.io')(server, {cors: '*'})
This works for me! : )
You can use the webpack to bundle the socket.io client into the background service worker.
To avoid the document issue mentioned by wOxxOm you can use jsonp: false option.
const socket = io('URL', {
jsonp: false,
});
i want to integrate pubnub with reactjs frontend and node js backend.My system consist of websocket . I want to replace websocket with pubnub connection .I have installed pubnub using npm in node js its works fine.But in front end side when i run npm start i see only below screen.
The problem with web socket is when connection lost i didnt get back my card details(poker game cards)
Did i do something wrong?if please let me know correct way to do it.
i have replaced websocket connection of existing system with pubnub.see code below.
import PubNub from 'pubnub';
import { PubNubProvider, usePubNub } from 'pubnub-react';
// import CountDownBgTask from "./containers/CountDownBgTask";
const pubnub = new PubNub({
publishKey: 'xxxxxxxxxxxxxxxxx',
subscribeKey: 'xxxxxxxxxxxxxxxxx'
});
componentDidMount() {
if (isMobile) {
setTimeout(() => {
this.setState({
isOpen: true
});
window.scrollTo(0,1);
},1000)
}
window.onbeforeunload = closingCode;
// Read res from service via Socket IO
// socket.on("message", receiveMsg);
pubnub.on("message", text => {
let params = text.split("|"); //.map(p => Base64.Decode(p)); // we are not using b64 now
let message = params.shift(); // message, eg. playerSitOut, clearTable
this.receiveMsg.push(message);
this.props.updateMessage({ message, params });
});
}
I'm trying to build a simple socket.io-client using nodejs, but I'm facing a trouble...
I'm connecting with the socket.io (server), but I can't emit any data. Follow bellow my simple code:
Client Side:
var socketIO = require('socket.io-client')('http://serverdns:3000');
socketIO.on("dashboard", (data) => {
console.log(data);
});
socketIO.on('connect', function(){
console.log("Connected with the translator service.");
socketIO.emit('dashboard', 'teste');
});
socketIO.on('disconnect', function(){
console.log("Disconnected from the translator service");
});
socketIO.on('error', function(err){
console.log(err);
});
Socket.io version: 2.1.1 (I've tried to use old versions but the same problem happens).
The connect event works, the log "Connected with the translator service." is generated, but emit does not work.
Server side:
var server = require('http').createServer();
var ioServer = require('socket.io')(server, { pingInterval: 2000, pingTimeout: 60000, cookie: false });
class SocketServer {
constructor() {
var self = this;
ioServer.on('connection', function (client) {
console.log('[SOCKETIO] AVAILABLE');
client.on('main', self.main);
client.on('disconnect', self.disconnect);
});
server.listen(3000);
}
getSocket(){
return ioServer;
}
main(data) {
console.log(data);
}
disconnect() {
console.log("[SOCKETIO] DISCONNECTED");
}
}
module.exports = new SocketServer();
Anyone can help me?
Are there anything I'm not seeing?
Thanks a lot.
Right now you are emitting to the event dashboard from client. But on the server side you have no code that is handling that event. You are currently logging the event main which does not match with what you're emitting. Try client.on('dashboard', self.dashboard). Make your own dashboard function.
Following the example from:
https://www.npmjs.org/package/pubnub
I am trying to set up a connection from my nodejs server to pubnub via:
var pubnub = require("pubnub").init({
publish_key: "pub key here",
subscribe_key: "sub key here",
channel: 'my_channel',
user: 'Server'
});
pubnub.subscribe({
channel: 'my_channel',
callback: function(message) {
console.log("Message received: ", message);
}
});
pubnub.publish({
channel : 'my_channel',
callback : function(e) { console.log( "SUCCESS!", e ); },
error : function(e) { console.log( "FAILED! RETRY PUBLISH!", e ); }
});
// test msg to see if server connect to pubnub channel
function publish() {
pubnub.publish({
channel : 'my_channel',
message : 'Server subscribed'
});
}
I thought this followed the example provided but my server will not show up in the pubnub log nor receive any SocketIO events from the 2 peers trying to connect to each other. I am trying to use pubnub with SocketIO to send over ice candidates to establish p2p video via WebRTC
For peers that are trying to connect that are actually do have a pubnub connection working, the set up is as follows:
(function() {
var pubnub_setup = {
channel: "my_channel",
publish_key: "pub key",
subscribe_key: "sub key",
user: user
};
var socket = io.connect( 'http://pubsub.pubnub.com', pubnub_setup);
// various socket.on( ... )
})();
#jerryfox, there is a connection callback on subscribe called "connect". You should only issue your test publish on this "connect" callback... otherwise, you can publish before you've actually connected, and you'll never see the message. Try this:
pubnub.subscribe({
channel: 'my_channel',
callback: function(message) {
console.log("Message received: ", message);
},
connect: publish
});
If you are still having issues, contact us at support#pubnub.com, and we'll help resolve the issue for you.
I am trying to develop a simple socket io based chat app using sails MVC.
whenever a client connected socket emitting multiple times(equa to number of clients).
here is my code.
Server :
io=req.socket.manager;
var users=[];
io.sockets.on('connection', function(client) {
console.log("connected");
users.push(client.id);
client.on("chat", function(data) {
io.sockets.sockets[data.to].emit("chat", { from: client.id, to: data.to, msg: data.msg });
client.emit("chat", { from: client.id, to: data.to, msg: data.msg });
});
});
Client :
var socket=new io.connect('http://localhost:1337/');
socket.request('/Chat/index');
socket.emit('connection',function(data){
console.log(data);
});
socket.on('connect', function() {
console.log("Connected.");
//
});
socket.on('chat', function(data) {
console.log(data.msg );
});
please help me , is there any way to get actual socket object in sails?
I am using io=req.socket.manager; which is of req object.
the socket object should be accessible in sails.io on the server side
link
maybe you want to answer to a unique socket id? that can be achieved this way:
In the file sockets.js, at your config folder, find the onConnect property and add code like this:
onConnect: function(session, socket){
sails.io.sockets.socket(socket.id).send('YOUR_EVENT', {'message' : 'your message to a unique socket'});
}
It will send a unique message when a new connection is established. Just a couple of notes:
This can be considered a socket.io issue, not a sails issue, since the method .socket(socket.id) is part of socket.io
This was tested on sails v0.9.8, in other versions the file sockets.js might not be included in the default generated app with sails' new command
This is just an example to show how can it be done, you might need to adapt it to your needs.
Hope this helps.