socket.io javascript don't work - javascript

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"

Related

chrome.tabs not giving output in browser console

I am working with browser's console and I want to fetch all the details of all the active tabs at the moment.What I am doing is opening browser's console and typing in this:
but this is giving me the following error:
VM713:1 Uncaught TypeError: Cannot read property 'query' of undefined
at <anonymous>:1:13
Thanks
Edit:
var http = require("http"),
io = require("socket.io"),
fs = require("fs"),
util = require("util");
var backlog_size = 2000;
var filename = process.argv[2];
if (!filename) return util.puts("Usage: node <server.js> <filename>");
var linesCount = 0;
// -- Node.js HTTP Server ----------------------------------------------------------
server = http.createServer(function (req, res) {
console.log(req.url)
filePath = req.url
if(filePath=="/"){
filePath='./index.html'
fs.readFile(filePath, function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading ' + filePath);
}
res.writeHead(200);
res.end(data);
});
}
else
{
if(filePath=="/client"){
filePath = './client.html';
fs.readFile(filePath, function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading ' + filePath);
}
res.writeHead(200);
res.end(data);
});
}}
});
server.listen(8000, "0.0.0.0");
var fsTimeout
var textToSend=""
// -- Setup Socket.IO ---------------------------------------------------------
var socket = io(server, {
cors: {
origin: "*",
},
});
socket.on("connection", function (client) {
fs.watchFile(filename, function (curr, prev) {
console.log("file changed");
// if (prev.size > curr.size) return { clear: true };
// var stream = fs.createReadStream(filename, {
// start: prev.size,
// end: curr.size,
// });
// stream.on("data", function (lines) {
// console.log(lines.toString());
// linesCount += count;
// console.log(linesCount);
// client.emit("tail", { lines: lines.toString("utf-8").split("\n") });
// });
if (prev.size > curr.size) return { clear: true };
if(!fsTimeout){
if(prev.ctime.getTime() != curr.ctime.getTime())
{
console.log("file changed")
var stream = fs.createReadStream(filename, {
start: prev.size,
end: curr.size,
});
stream.on("data", function (lines) {
console.log(lines.toString());
textToSend+=lines.toString();
textlen=textToSend.split("\n").length;
// count=lines.toString().split("\n").length
// linesCount += count;
// console.log(linesCount);
console.log(textlen)
if(textlen<10)
{
console.log("me")
socket.emit("tail", { lines: lines.toString("utf-8").split("\n") });}
else
{
console.log("client")
socket.emit("room", { lines: textToSend.toString("utf-8").split("\n") }); };
});
}
fsTimeout = setTimeout(function() { fsTimeout=null }, 5000)}
}
);
});
This is the edited code that I used and made it working using socket.io
1
I am working on a node.js app where I am using socket.io to send data to multiple clients but the socket is only able to send data to one client i.e if I open my webpage in two tabs its not working in both the tabs but when I open just 1 tab of webpage it is able to transmit the data.I dont know why? Can someone help,Here's my code:
server.js
The reason for this is a chrome.tabs is a chrome extension API's object. You can not access this with chrome's dev console.
Tabs documentations
Chrome Extention Quick Start Guide

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('');
});

Elasticsearch.js - wait for ping to complete, async call

I am playing with elasticsearch.js from the browser. I would like to ping elasticsearch, wait for the request to complete and then return the result of the connection. But right now it is happening asynchronously, and returning undefined even when the connection is ok. I have code like this:
var connectionOK = false;
function createElasticsearchClient(hostAddress) {
var client = new $.es.Client({
hosts: hostAddress
});
return client;
}
function checkElasticsearchConnection(client) {
$.when(pingElasticsearch(client)).done(function () {
return connectionOK;
});
}
function pingElasticsearch(client) {
console.log("ELASTICSEARCH: Trying to ping es");
client.ping({
requestTimeout: 30000,
// undocumented params are appended to the query string
hello: "elasticsearch"
}, function (error) {
if (error) {
console.error('ELASTICSEARCH: Cluster is down!');
connectionOK = false;
console.log("INSIDE: " + connectionOK);
} else {
console.log('ELASTICSEARCH: OK');
connectionOK = true;
console.log("INSIDE: " + connectionOK);
}
});
}
and how it is used:
var esClient = createElasticsearchClient("exampleserver.com:9200");
var esCanConnect = (checkElasticsearchConnection(esClient));
You're mixing asynchronous functions with synchronous functions. You could go with this approach instead:
function createElasticsearchClient(hostAddress, callback) {
var client = new $.es.Client({
hosts: hostAddress
});
return callback(client);
}
function pingElasticsearch(client, callback) {
console.log("ELASTICSEARCH: Trying to ping es");
client.ping({
requestTimeout: 30000,
// undocumented params are appended to the query string
hello: "elasticsearch"
}, function (error) {
if (error) {
return callback('ELASTICSEARCH: Cluster is down!');
} else {
return callback(null);
}
});
}
And then run
createElasticsearchClient("exampleserver.com:9200", function(esClient) {
pingElasticsearch(esClient, function(err) {
if (err) console.log(err);
else {
//Everything is ok
console.log('All good');
}
});
});

PeerJS peer not receiving data

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);
});
});
});

Categories

Resources