i try to learn node.js and try to create a new TCP Server connection. The code
var server = require('net').createServer(function(socket) {
console.log('new connection');
socket.setEncoding('utf8');
socket.write("Hello! You can start typing. Type 'quit' to exit.\n");
socket.on('data', function(data) {
console.log('got:', data.toString());
if (data.trim().toLowerCase() === 'quit') {
socket.write('Bye bye!');
return socket.end();
}
socket.write(data);
});
socket.on('end', function() {
console.log('Client connection ended');
});
}).listen(4001);
look at the callback function, after then, they call listen method. What is this for kind of object.
What it basically says is:
function myHandler(socket) {
// everything up to socket.on('end')
}
var server = require('net').createServer(myHandler);
server.listen(4001);
So it's just creating a socket server with a handler function, and then make the server listen to port 4001.
Related
I just started picking up socket.io. I'm trying to use it in angular.js and everything works fine. However, it keeps returning multiple times
in my controller.js
socketio.emit('GameOver',$scope.currentPlayer.Name);
socketio.on('GameOverEmit',function(data){
if(data === $rootScope.user.user_name){
var result = {
opponent : rdyplayers.user_name,
result : "won"
};
// keep getting multiple result
console.log(result);
}else{
var result = {
opponent : rdyplayers.user_name,
result : "lose"
};
// keep getting multiple result
console.log(result);
}
});
In my server.js
io.sockets.on('connection', function (client) {
client.user_name = user.user_name;
//Useful to know when someone connects
console.log('\t socket.io:: player ' + client.user_name + ' connected');
// playerturn
client.on('PlayerTurn',function(data){
io.emit('PlayerTurnEmit',data);
});
// game over
client.on('GameOver',function(data){
io.emit('GameOverEmit',data);
});
// button disabled
client.on('PlayerButtonDisabled',function(data){
io.emit('PlayerButtonDisabledEmit',data);
});
//When this client disconnects
client.on('disconnect', function () {
//Useful to know when someone disconnects
console.log('\t socket.io:: client disconnected ' + client.user_name );
io.emit("disconnected",client.user_name);
}); //client.on disconnect
}); //io.sockets.on connection
Am I using socket.io in the correct way? In order to broadcast the data to everyone I just pass the data into an emit and take the data broadcast it by using on like pass the data to server and pass it back to the front-end?
For broadcast use socket.broadcast.emit()
I don't find any socket disconnection listen event code in your client side code.. try adding socketio.disconnect for disconnection for client side
And also add a listener to the socket disconnection emit event from server to client ..on the client side by adding socketio.on('disconnect', function(){do something})
it caused by controller.js, whenever i revisit the page it will establish a new socket so what i did is whenever a user leave or close the tab it removes all the listener.
i ended up solving it by adding getsocket in my service.js
ttt.factory('socketio', ['$rootScope', function ($rootScope) {
'use strict';
var socket = io.connect();
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
});
},
getSocket: function() {
return socket;
}
};
}]);
and in my controller.js i do
$scope.$on('$destroy', function (event) {
socketio.getSocket().removeAllListeners();
});
I have a websocket where I need to send two messages. It looks like the second message isn't being received. I'm not sure if this is a problem with my code or the websocket itself. I've used the Chrome Advanced Rest Tools Client and was able to send both messages successfully, but I'm not sure why it's not working in my code.
var ws = new WebSocket('ws://localhost:15449/');
ws.on('open', function open() {
console.log('i am open');
ws.send(JSON.stringify(data1));
//ws.send(JSON.stringify(data2));
ws.emit('sendData2');
});
ws.on('sendData2', function sendBar() {
console.log('testing!!');
ws.send(JSON.stringify(data2));
});
ws.on('message', function message(msg1, msg1) {
//the data received is a buffer
console.log('received:', msg1, msg1);
ws.close();
done();
});
Is there not a way to distinguish the different data that is being sent in ws.on('message')?
I figured it out. I needed to add an if check to make sure i got the first data and then send the second one.
var ws = new WebSocket('ws://localhost:15449/');
ws.on('open', function open() {
console.log('i am open');
ws.send(JSON.stringify(data1));
});
ws.on('message', function message(msg) {
if(...) {
ws.send(JSON.stringify(data2));
}
console.log('received:', msg);
ws.close();
done();
});
I'm trying to 'emit' data to the server, but nothing is happening.
The console says that I've connected, but it won't log anything whenever
I try to emit the specific command.
Clientside (JQuery/JS):
var ip = "";
$.ajax({
url : "../host",
success : function(result){
ip = result;
}
});
var socket = io.connect(ip);
socket = io('/admin');
socket.on('add_task', function(name, event, command, args) {
AddTask(name, event, command, args); //I get this data from the server
});
socket.on('remove_task', function(name) {
DeleteTask(name); //I get this data from the server.
});
$("#addTask").click(function() {
var args = ["add", $("#nameData").val(), $("#eventData").val(), $("#commandData").val(), $("#argData").val()];
socket.emit("task", args); //This won't emit anything.
$("#add-modal").modal("hide");
});
Serverside (NodeJS):
admin.on('connection', function(socket) {
console.log("An admin has connected."); //This logs
task.get().forEach(function(tsk) {
var tdata = tsk.split(':');
admin.emit('add_task', tdata[0], tdata[1], tdata[2], tdata[3]); //This sends
});
admin.on('task', function(args) {
console.log(args); //This doesn't log
});
});
You need to listen for the event on the connected socket, like so:
admin.on('connection', function(socket) {
socket.on('task', function(args) {
console.log(args);
});
});
This is because the event comes from the connected socket, otherwise socket.io would have no way of knowing which socket the event came from and the event's associated data would be meaningless.
I have the following code:
function Socket(io, playGame, mapper) {
io.on('connection', function (socket) {
// message handler for the chat message
socket.on('sendChat', function (data) {
console.log(socket);
console.log(data);
console.log('recieved chat');
var connectedPlayer = playGame.findConnectedPlayer(socket);
if (!connectedPlayer)
return;
var connectedGame = playGame.findConnectedGame(socket, connectedPlayer.gameId);
if (!connectedGame)
return;
// send update game with players properly ordered
for (socketIndex in this.sockets) {
var socket = this.sockets[socketIndex];
// send the new data to each player
socket.socket.emit('chatUpdate', { chatText: data.chat });
}
});
// message handler for join game message
socket.on('joinGame', function (data) {
console.log('recieved join:', JSON.stringify(data));
if (!playGame.newConnectedPlayer(socket, data))
return;
...
In the method for sendChat, socket is undefined. In the method for joinGame, socket is defined. I have tried several ideas, but the problem persists. Any help would be appreciated.
You'll have to rename one of the 2 socket variables -- either the parameter for 'connection' or the var in the loop:
io.on('connection', function (socket) {
for (socketIndex in this.sockets) {
var socket = this.sockets[socketIndex];
The var is shadowing the parameter, rendering the parameter inaccessible.
This happens in part because the var socket doesn't only exist within the for loop. JavaScript vars are function-scoped and their declarations are hoisted to the top of the function, as in:
socket.on('sendChat', function (data) {
var connectedPlayer, connectedGame, socket; // each initially `undefined`
console.log(socket);
// ...
for (socketIndex in this.sockets) {
socket = this.sockets[socketIndex];
// ...
});
And, having the same exact name, at most only one of them can be reached from a particular function.
Also note that the for loop and var socket aren't really necessary.
You can use the Socket.IO Server's own .emit() method to send a message to all clients.
io.emit('chatUpdate', { chatText: data.chat });
I am trying to set up a node js server to do push notifications to my browser app. I have a basic example working, but I am wondering how to send data up to the server from the client on handshake.
I Need to send to the server something like a user id, so when a notification comes in for them, it can be routed back to the user.
my server looks something like this
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs');
app.listen(8000);
function handler ( req, res ) {
res.writeHead( 200 );
res.end('node working');
};
io.sockets.on( 'connection', function ( socket ) {
socket.volatile.emit( 'notification' , "blah" );
});
and my client looks something like this
var socket = io.connect('http://localhost:8000');
socket.on('notification', function (data) {
//prints data here
});
In socket.io, the emit is essentially like any other event handler (e.g. jQuery's .on('click'...)); you declare the event and send the data. On the server, you add the .on('event', ...) to catch the request and process it.
The socket.io front page shows this example for the 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);
});
});
And this for the client:
<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>
It sounds like the part you're looking for is the socket.emit portion.
I have done this sort of thing in the past by setting a cookie on the client (which you're probably doing anyway), and then using socket.io's authorization event. You can use this event to decide whether to even accept the socket connection to the user in the first place.
io.configure(function () {
io.set('authorization', function (handshakeData, callback) {
var cookie = handshakeData.headers.cookie;
// parse the cookie to get user data...
// second argument to the callback decides whether to authorize the client
callback(null, true);
});
});
See more documentation here: https://github.com/LearnBoost/socket.io/wiki/Authorizing
Note that handshakeData.headers.cookie is just a string literal representation of the cookie, so you'll have to do your own parsing.