Socket.io client cannot emit message - node.js

Server:
var
io=require('socket.io'),
express=require('express'),
UUID=require('node-uuid'),
path=require('path'),
app = express();
app.configure(function(){
app.use(express.static(path.join(__dirname,'')));
});
var server = require('http').createServer(app).listen(8080);
sio = io.listen(server);
app.get('/', function(req, res){
res.sendfile('/index.html', {root:__dirname});
});
sio.sockets.on('connection', function(socket){
socket.userid = UUID();
socket.on('message', function(){
console.log('client just sent something');
socket.emit('news', { hello: 'world' });
});
});
Client connects index.html at first, then click a href to gameroom.html. This is gameroom.html:
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript" src="game.room.js"></script>
<script type="text/javascript" src="client.js"></script>
</head>
</html>
client.js:
window.onload = function(){
var game = new game_room();
}
game.room.js:
var game_room = function(){
this.socket = io.connect();
this.socket.on('connect', function(){
this.socket.emit('message', 'Hello server');
});
}
When the client connects, it should emit the message and the server writes the log, but I didn't get any log. I tried the code without this.socket.on('connect') in game.room.js, and the client can emit the message and I got the log. Also, if I transfer the code from game.room.js to client.js, i.e. in window.onload I created var socket = io.connect() and socket.on('connect', function() {socket.emit('messsage', 'Hello server')}); it works fine.
Can someone help me out or explain what is happening? Thanks.

You are loosing context you could try bind:
var game_room = function(){
this.socket = io.connect();
this.socket.on('connect', function(){
this.socket.emit('message', 'Hello server');
}.bind(this));
}
or you could just set this.socket to some local var:
var game_room = function(){
var socket = this.socket = io.connect();
this.socket.on('connect', function(){
socket.emit('message', 'Hello server');
});
}

Related

How to write tests: Socket.io app unit testing

I am trying to make simple chat app using socket.io. Manually it's working fine (via browser localhost:3000/) but I want to write unit tests to verify logic of the server. I don't know which tools/libraries to use for testing.
Here is my node server code:
index.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var socketCount = 0;
http.listen(3000, function(){
console.log('listening on *:3000');
});
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket) {
socketCount++;
console.log('new user connected');
// Let all sockets know how many are connected
io.emit('users connected', socketCount);
socket.on('disconnect', function(){
// Decrease the socket count on a disconnect, emit
socketCount--;
io.emit('users connected', socketCount);
});
socket.on('chat message', function(msg){
// New message added, broadcast it to all sockets
io.emit('chat message', msg);
});
});
And here is my html page:
file: index.html
<html>
...
<body>
<ul id="messages"></ul>
<div class='footer'>
<div id="usersConnected"></div>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</div>
</body>
...
<script>
$(document).ready(function(){
$('#messages').val('');
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
// New message emitted, add it to our list of current messages
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
// New socket connected, display new count on page
socket.on('users connected', function(count){
$('#usersConnected').html('Users connected: ' + count);
});
});
</script>
</html>
Thanks.
I had this problem: How to do unit test with a "socket.io-client" if you don't know how long the server take to respond?.
I've solved so using mocha and chai:
var os = require('os');
var should = require("chai").should();
var socketio_client = require('socket.io-client');
var end_point = 'http://' + os.hostname() + ':8081';
var opts = {forceNew: true};
describe("async test with socket.io", function () {
this.timeout(10000);
it('Response should be an object', function (done) {
setTimeout(function () {
var socket_client = socketio_client(end_point, opts);
socket_client.emit('event', 'ABCDEF');
socket_client.on('event response', function (data) {
data.should.be.an('object');
socket_client.disconnect();
done();
});
socket_client.on('event response error', function (data) {
console.error(data);
socket_client.disconnect();
done();
});
}, 4000);
});
});

Socket.io Client Side socket.io#0.9.16

My problem is that I can connect to my client via html/js but I cannot do the same thing using node. I am using socket.io#0.9.16 .
var io = require('socket.io');
var socket = io.connect('https://website.com:3000');
socket.on('connect', function (data) {
socket.emit('room', 'connecting');
})
socket.on('message' , function (data){
console.log("message has been sent");
});
vs
<html>
<script src="https://website.com:3000/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect('https://website.com:3000');
socket.on('connect', function (data) {
socket.emit('room', 'connecting');
})
socket.on('message' , function (data){
alert(data.message);
});
</script>
</html>
npm install socket.io-client#0.9.16
var io = require('socket.io-client');
var socket = io.connect('https://website:3000') ;
socket.on('connect', function (data) {
socket.emit('room', 'foo');
console.log('connecting... working...')
});
socket.on('someRoom' , function (data){
console.log('update ...');
console.log(data);
});
You don't want socket.io, you need to use socket.io-client.
var socket = require('socket.io-client')('https://website.com:3000');
socket.on('connect', function(){
socket.emit('room', 'connecting');
socket.on('message' , function (data){
alert(data.message);
});
});

Socket.io gives Welcome to socket.io message

Here is my server
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Here is my client index.html
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:80');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
Here are my commaneds
node server.js
and on browser I am hitting URL localhost:80/index.html
after hitting above URL I am getting message
Welcome to socket.io.
I am using nodeJS v0.10.9
socket.io provides a socket.io server, not a web server. So index.html in the context of socket.io doesn't exist.
Instead, you could use Express to provide a basic web server, combined with socket.io to provide messaging:
// server.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
app.use(express.static(__dirname + '/public'));
server.listen(80);
// ./public/index.html
<!doctype html>
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect(); // let socket.io autodiscover the server
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>

After connecting to server client-side code does not response

Whenever I execute my code, I get message at console that it's connected than after that that nothing happens.
Here is the code:
server-side
var app = require('express')()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
server.listen(80);
app.get('/', function (req, res) {
res.sendfile('index.html');
});
io.sockets.on('connection', function (socket) {
console.log('m connected');
socket.emit('news', { hello: 'm joooon ' });
socket.on('my other event', function (data) {
console.log(data);
});
});
client-side
<!DOCTYPE html>
<html>
<head>
<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>
</head>
<body>
<div id="lo">magudi</div>
</body></html>
On the client side, your not listening to the port.
var socket = io.connect('http://localhost:80');

node.js + socket.io example: client connects but socket.send() from client to server fails

server code
var http = require('http'),
io = require('socket.io'),
fs = require('fs');
respcont = fs.readFileSync('socketio.client.js');
server = http.createServer(function(req, res){
// your normal server code
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(respcont);
});
server.listen(8080);
// socket.io
var socket = io.listen(server);
socket.on('connection', function(client){
// new client is here!
client.on('message', function(){ console.log('message arrived'); })
client.on('disconnect', function(){ console.log('disconnected'); })
});
client code
<html>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = new io.Socket(null,{port:8080,rememberTransport:true,timeout:1500});
socket.connect();
socket.on('connect', function(){ console.log('connected to server'); socket.send('hi there, this is a test message'); })
socket.on('message', function(){ console.log('recieved a message!'); })
socket.on('disconnect', function(){ console.log('disconnected from server'); })
</script>
</body>
</html>
looks like node.js HEAD was broken.
git pull to 0474ce67908c9afddab69d3f0eb53564b10e2ad1 fixed the problem.

Resources