socket.io-client connecting, but not emitting - javascript

I am making a little encrypted chat app, in the terminal, using socket.io-client and socket.io. The client is able to connect to the server, but is not emitting the username, when its entered.
Client:
var socket = require('socket.io-client')('http://127.0.0.1:3000');
socket.on('connect_error', function(){
console.log('Failed to establish a connection to the servers, or lost connection');
return process.exit();
});
var prompt = require("prompt-sync")()
var news = "Add news: Will be from database. "
var username = prompt("Username>: ")
console.log("Hold on a sec, just checking that!")
console.log("")
if (typeof username === "defined"){
socket.emit('user-name', {usr: 'username'})
}
socket.on('user-name-good',function(socket){
console.log("Okay! Your username looks good, we just require your password")
console.log("If you chose to have no password, please press enter with out pressing space!")
var password = prompt("Password>: ")
if (typeof password !== "defined"){
console.log("Please provide a password!")
return password = prompt("Username>: ")
}
socket.on('user-name-fail',function(socket){
console.log("Sorry, we could not find, "+username+""+"Please register on the website, or, if you have registered ")
return process.exit()
})
}
)
Server code, is based on code from socket.io chat example:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
I have added a error event, this closes the client if a connection to the server fails, so I know its connecting, any help appreciated, I have done research on this topic, and tried a lot of other methods, but to no avail.
Also the connection is made after you submit data, not when the client code is started, what could be causing this?

If you want to send events between client and server you have to:
Send event A from client to the server and server has to be listening for the A event.
If you want to send event B from server to client then client has to be listening for the event B.
Apart from everything else in your code I don't see where you are listening for the 'chat message' event on the client side.
Socket.io is based on these so called 'events'. The code below is going to send 'my_event' event to the server and the trasmitted data is going to be the object { a: 1 }.
socket.emit('my_event', { a: 1 });
If I want to handle this event on the server I have to listen for it:
socket.on('my_event', function(data) {
// data is the object { a: 1 }
// do stuff..
});

Related

client code in node js

I am new to Nodejs and am trying to set up a server client connection using sockets. Below is my code. Server is working OK but client is not connecting.
Please can anyone help me figure out the mistake.
Much Thanks
jessi
Server.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
io.on('data', function(data) {
console.log('DATA from client is: ' + data);
// Close the client socket completely
});
server.listen(4200);
console.log('Monitoring server listening on port 4200');
Client.js
var HOST = '127.0.0.1';
var PORT = 4200;
var express = require('express');
var app = express();
var client = require('http').createServer(app);
var io = require('socket.io')(client);
client.connect(PORT, HOST, function()
{
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
// Write a message to the socket as soon as the client is connected,
// the server will receive it as message from the client
io.write('I am Chuck Norris!');
});
// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {
console.log('DATA: ' + data);
// Close the client socket completely
client.destroy();
});
// Add a 'close' event handler for the client socket
client.on('close', function() {
console.log('Connection closed');
});
For the client you use the socket.io-client package instead. The client side doesn't require the use of the Express portion since you're not recreating a web server on the client. If you look at your current code you're essentially recreating the Socket server which isn't what you want to do.
All that is necessary is to create a new Socket.io client and register your various event handlers.
var socket = require('socket.io-client')('localhost:4200');
socket.on('data', function(data) {
// handle incoming data
console.log(data);
});

How can I have faye-websockets code running in the browser?

I'm new with node.js/express and all and I want to be able to notify any clients in browser about a new message received from some algorithm in the back-end. The publisher algorithm connect to the websocket and writes the message.
As far as I've looked there were examples which recommended websockets but I haven't been able to run that code in browser only in console.
Example client code:
var WebSocket = require('faye-websocket');
var ws = new WebSocket.Client('ws://localhost:1234');
var http = require('http');
var port = process.env.PORT || 1235;
var server = http.createServer()
.listen(port);
// receive a message from the server
ws.on('message', function(event) {
alert(JSON.parse(event.data));
});
Thank you
Found the answer after some trial/error iterations.
The algorithm now does a POST to an URL which in turn triggers a write to sockets for all connected clients via socket.io.
Client code:
var socket = io('http://localhost:7777');
socket.on('message', function (msg) {
document.body.insertAdjacentHTML( 'beforeend', '<div id="myID">'+msg+'</div>' );
});
And on the server, when client connects I retain it's socket into an array so I can write to each one:
Server code:
io.on('connection', function(socket){
console.log('a user connected: '+socket.id);
var id = clientCount++;
clientSockets[id] = socket;
socket.on('disconnect', function(){
console.log('user disconnected');
delete clientSockets[id];
socket = null
});
});
app.post('/alerts', function(req, res) {
req.accepts(['json', 'application']);
console.log("Algo did a POST on /alerts!");
// send the message to all clients
//console.log(req.body);
for(var i in clientSockets) {
clientSockets[i].send(JSON.stringify(req.body));
}
res.send(200);
});
In conclusion, I'm not using faye-websockets but instead socket.io

How to host a socket.io server and a http server together?

I have a Socket.io server and a basic HTTP server that I coded together, but the problem is that the HTTP-server tries to serve requests that socket.io should serve.
Code:
//Dependences
var sio = require('socket.io');
var http = require("http");
var NewRequestHandler = require('./NewRequestHandler').Handler;
var DisconnectHandler = require('./DisconnectHandler').Handler;
var AuthorisationRequestHandler = require('./AuthorisationRequestHandler').Handler;
//The backlog of resources
var ResourceBackLog;
var ResourceRequestHandler = require("./ResourceRequestHandler").Handler;
//Reports the IP adress and Port that it will run on.
console.log('IP address: ' + process.env.IP);
console.log('Port: ' + process.env.PORT);
//Creates and configures a new http.server instance.
var Server = new http.Server();
//Starts both the http and socket.io server.
var io = sio.listen(Server.listen(process.env.PORT, process.env.IP, ResourceBackLog, function(error) {
if (error) {
console.log("Error: " + error);
} else if (!error) {
console.log("Server started sucsessfully.");
Server.on('request', ResourceRequestHandler);
console.log("Server now ready for requests.");
}
}));
//Handles the connect and authorisation bit
io.sockets.on('connection', function(socket) {
console.log('New Connection');
socket.on('auth', function(Keys) {
console.log('Autorisation Request Recived');
AuthorisationRequestHandler(socket, Keys, function() {
socket.on('NewRequest', function(Request) {
NewRequestHandler(socket, Request);
});
socket.on('diconnect', function() {
DisconnectHandler(socket);
});
});
});
});
The ResourceRequestHandler is the file that serves resources by checking the URL then opening the file at that location,
but it also serves /socket.io requests.
I would have Socket.io listen on another port and have the regular http server direct requests to it that way you can be sure they won't interfere with each other.
// create server
io = http.createServer();
io.on('uncaughtException', function(exception) {
console.log(exception);
});
io.listen(4001);
http.createServer(RequestHandler) and new http.Server(RequestHandler) work
Based on Socket.IO 0.9.6.
It is important to attach your custom request listener before the socket.io one. Socket.IO will then serve the requests it can and delegate all the others to your own request listener.
The algorithm in socket.io/lib/manger.js, is as follows.
In constructor:
1. remove all the existing request listeners.
2. attach Socket.IO request listener.
On request:
1. try to handle the request.
2. if Socket.IO cannot handle it, it delegates the request to the original listeners - those which were earlier removed in the constructor.

How to create custom client events in node.js + socket.io

I'm just starting out with node.js, and from what I can tell so far, the way clients communicate with the server is through:
//Client Code 1
var iosocket = io.connect();
iosocket.on('connect', function () {
iosocket.send("Here's some info");
});
The server becomes aware of this when the 'message' event is recieved:
//Server Code 1
var socketio = require('socket.io');
var io = socketio.listen(server);
io.sockets.on('connection', function (client) {
client.on('message', function(msg) {
//msg== "Here's some info"
}
});
Now I want the client to be able to provide several distinct events such as:
//Server Code 2
client.on('buttonClicked', function() { ...
client.on('nameChanged', function(newName) { ...
But I'm having trouble figuring out how. The only solution I can come up with using the pieces I have is to send back messages, but have them contain key-value pairs of information:
//Server Code 3
client.on('message', function(msg) {
kvp = message.split(',');
if( kvp[0] == 'buttonClicked' )
...
else if( kvp[0] == 'nameChanged' )
...
}
But I'm certain there's a proper way of doing this that I just haven't seen in any examples yet. I expect that there's something similar to how the server can generate any event it wants using:
//Server Code 4
io.sockets.emit('serverCustomEvent', eventData);
Which are in turn monitored by the client using:
//Client Code 4
iosocket.on('serverCustomEvent', function(data) {
//process data
});
Can someone point me in the right direction?
You can use emit on the client to send custom messages to the server.
iosocket.emit('serverCustomEvent', data);
and on the server
io.sockets.on('connection', function(socket) {
socket.on('serverCustomEvent', login);
});

Socket.io broadcast stops working if user leaves namespace then rejoins

My situation is this:
User A creates namespace with name of his choice
User B joins created namespace
User A sends message which is broadcasted by the server and received by User B
User B sends message which is broadcasted by the server and received by User A
User B leaves namespace through client-side socket.disconnect();
User B rejoins namespace
User B sends message which is broadcasted by the server and IS received by User A
User A sends message which is broadcasted by the server and NOT received by User B
Important Notes:
If User B refreshes the page and rejoins that namespace while User A remains there, he can
then send and receive messages normally again.
When User B is in the 'not working' state, he still seems to be getting events through socket emit. In other words, only User A receives events initiated by both parties, where User B only receives events initiated by himself.
Why, when User B leaves and rejoins does the server become a one way street relative to him?
Server Code:
var app = require('express')()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
server.listen(8080);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
var connection_function = function(socket) {
socket.on('join_chat', function(data) {
socket.set('fb_id', data.id);
socket.emit('joined_chat', data);
socket.broadcast.emit('joined_chat', data);
socket.namespace.connected_users[data.id] = data;
});
socket.on('send_message', function(data) {
data.user = socket.namespace.connected_users[socket.store.data.fb_id];
socket.emit('recieve_msg', data);
socket.broadcast.emit('recieve_msg', data);
});
socket.on('disconnect', function () {
socket.broadcast.emit('left_chat', socket.namespace.connected_users[socket.store.data.fb_id]);
delete socket.namespace.connected_users[socket.store.data.fb_id];
});
}
var chats = {};
var main = io.of('/main');
main.on('connection', function(socket) {
socket.on('new_chat', function(data, fn) {
if(!chats.hasOwnProperty(data.chat_name)) {
chats[data.chat_name] = io.of('/' + data.chat_name);
chats[data.chat_name].on('connection', connection_function);
chats[data.chat_name].connected_users = {};
}
fn(data);
});
});
Update (Friday October 12, 2012)
After some more research it appears that the issue may be with socket.io:
https://github.com/LearnBoost/socket.io-client/issues/251
https://github.com/LearnBoost/socket.io-client/issues/473
Are you sure you don't want to be using socket.io rooms instead?
socket.join(roomName);
io.socket.in(roomName).emit(.....;
I have a working example of rooms here: https://github.com/rcpeters/openMap_me/blob/master/app.js

Categories

Resources