I'm using PhantomJS 2.0 and trying to test socket.io between PhantomJS and NodeJS. It works but it takes alot of time for each connection (about 1000ms). I have tried on Chrome and it takes only 1-2ms. It's seems that socket.io in page.evaluate of PhantomJS is not socket.io!
Here is my testing code using CasperJS:
var casper = require('casper').create({
clientScripts:["socket.io.js"]
});
casper.start('http://localhost:8080');
casper.page.onConsoleMessage = function(msg) {
console.log(msg);
};
};
casper.then(function(){
this.evaluate(function(){
var socket = io.connect('http://localhost:8080');
socket.on('news', function (data) {
socket.emit('senddata', { time: new Date().getTime() });
});
})
})
casper.wait(5000);
casper.run();
On NodeJS server I use this code:
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var 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.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('senddata', function (data) {
console.log(new Date().getTime()-data.time);
});
});
The result of time measuring is always >= 1000ms. I need to tranfer data in serveral ms. Can anyone help me.
Thanks
Related
Good day, I'm trying to use socket.io i facing some problem with 404 not found. I'm using :84 as my xampp port
Folder structure
--tests
--node_modules
--app.js
--index.html
Here is my html content
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:84/test/');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
and this app.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) {
console.log(data);
});
});
I'm bit confuse about setting this part
var socket = io.connect('http://localhost:84/test/');
and this part
app.listen(8080);
I'm using windows 7 64 bit and i'm using xampp to run it. When i run it i get 404 error like this
"NetworkError: 404 Not Found - http://localhost:84/socket.io/?EIO=3&transport=polling&t=Ll8amII"
how can i fix it? sorry for my english and thanks in advance.
You are connecting to the wrong port.
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost:8080'); // CHANGE HERE
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', {my: 'data' });
});
</script>
XAMPP has nothing to do with express.
I've implemented a websockets api on top of a swagger-express node server.
For websockets I'm using express-ws which utilises the excellent ws library.
However I have come across a problem where the function setInterval is not being called when a websocket client connects.
Confusingly though in the ws.on('connection' function the console.log('websocket connected'); does execute while the setInterval function does not.
Can someone please point out what is wrong with my code?
'use strict';
var SwaggerExpress = require('swagger-express-mw');
var app = require('express')();
module.exports = app; // for testing
var expressWs = require('express-ws')(app);
var IndexWS = require('./api/controllers/indexWS');
var config = {
appRoot: __dirname // required config
};
app.ws('/', function(ws, req) {
ws.on('connection', function(conn) {
console.log('websocket connected');
setInterval(function timeout() {
console.log('conn');
}, 500);
});
ws.on('close', function() {
console.log('The connection was closed!');
});
ws.on('error', function() {
console.log('websocket error!');
});
ws.on('message', function(msg) {
setTimeout(function timeout() {
ws.send("500 delay");
}, 500);
});
console.log('websocket connected');
});
SwaggerExpress.create(config, function(err, swaggerExpress) {
if (err) { throw err; }
// install middleware
swaggerExpress.register(app);
var port = process.env.PORT || 3030;
app.listen(port, '0.0.0.0');
if (swaggerExpress.runner.swagger.paths['/hello']) {
console.log('server running on port ' + port );
}
});
I am very new to nodejs and I have some client-server implementation, which basically works the following manner : I submit a form which throws data to a client remote server. The latter send me back some new data.
net.createServer(function (socket) {
socket.on('error',function(err){ console.error(err)});
socket.on('data', function (data) {
some_method(data)
});
socket.on('end', function() {
console.log('CONN: disconnected');
//socket.end();
});
app.post('/api/sender', function(req, res) {
socket.write(some_input);
res.end();
});
}).listen(9000);
This works well until the client disconnects itself and reconnects, then I get the following error message :
{ [Error: This socket has been ended by the other party] code: 'EPIPE' }
And the code crashes at this line socket.write(some_input). Can someone can help ?
here's how this could be tackled :
module.exports = function(app) {
var clients = {};
var server = net.createServer(function (socket) {
server.getConnections(function(err, count) {
var id = sha1(socket.remoteAddress);
clients[id] = {
stream: through(),
socket: socket,
}
clients[id].stream.pipe(socket);
});
socket.on('error',function(err){ console.error(err)});
socket.on('data', function (data) {
some_method(data)
});
socket.on('end', function() {
console.log('CONN: disconnected');
socket.end();
});
app.post('/api/sender', function(req, res) {
// here id is the IP adress got from req
if (clients[id]) {
clients[id].stream.write(input);
}
res.end();
});
}).listen(9000);
};
I am new to Node and Socket.io and attempting to get the below code running. It is designed to service WebSocket requests, however I would like to amend it to also serve static content such as index.html.
My web socket code is as follows:
var http = require("http"),
sys = require("sys"),
io = require("socket.io"),
GlobTrie = require("glob-trie.js");
var Brokaw = {};
Brokaw.Server = function(port) {
var self = this;
// setup the basic HTTP server -- socket.io will wrap this
var server = http.createServer(function(req, res) {
// We have to respond with something, otherwise the connections hang :(
res.writeHead(404);
res.close();
});
server.listen(port);
this._io = io.listen(server, { "resource": "brokaw" });
this._trie = new GlobTrie();
this._io.on("connection", function(conn) {
new Brokaw.Server.Client(conn, self);
});
};
new Brokaw.Server(8080);
And my code to serve the index.html is as follows:
// Hardcode *all* HTTP requests to this server to serve up index.html
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);
}
);
Can anyone advise on how to integrate the two i.e. amend the top code to serve my index.html file also?
Appreciate any comments, and I have been struggling for many hours!
Regards, Ben.
There is an example, taken from the official Socket.IO homepage:
Server-side:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(80);
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) {
console.log(data);
});
});
Client-side:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
I'm trying an example of WebSocket to develop a simple chat.
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 + '/test.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
and test.html:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('connect', function() {
alert('<li>Connected to the server.</li>');
});
socket.on('message', function(message) {
alert(message);
});
socket.on('disconnect', function() {
alert('<li>Disconnected from the server.</li>');
});
function sendF(){
var message = "Test";
socket.send(message);
alert('Test Send');
}
In test.html I have also a simple button that onClick call sendF.
If I try it I see on my browser an alert when I CONNECT, SEND, and DISCONNCT, and if I check in console, I see the message.
But I cannot receive the same message in response from server, to show it in my browser! I think socket.on('message'... is not working for me!
Your server.js is missing event listeners. It's also missing where you are doing the send of the message to be displayed in the browser.
io.sockets.on('connection', function (socket) {
console.log('user connected');
socket.send('hello world');
socket.on('disconnect', function () {
console.log('user disconnected.');
});
socket.on('message', function (data) {
console.log(data);
});
});