What is difference between socket.on and io.on? - javascript

Server side code:
io.on('connection',(socket)=>{
console.log('New WEBSocket Connection')
socket.emit('message',"welcome")
socket.broadcast.emit('message',"A new user joined")
socket.on('textMessage',(message,callback)=>{
const filter = new Filter();
if(filter.isProfane(message)){
return callback('Mind your languezz')
}
io.emit('message',message)
callback()
})
}
Client side code:
socket.emit('textMessage',message,(error)=>{
if(error){
return console.log(error)
}
console.log("Message Delivered")
})
My doubt is, on client side code, what if I used io.on instead of socket.on?
socket.on('textMessage',(message,callback)=>{............instead I did it like this:
io.on('textMessage',(message,callback)=>{.............

io.on listens to the server events. connection is an event on the server, when a socket is connected. And when that socket is connected, the callback function inside that is run.
socket.on listens to events on that connected socket. socket.on('textMessage' asks to do something when textMessage event is emitted on the socket, which you do from your client using socket.emit('textMessage'

Related

Why does my socket.io app disconnect immediately when run on Raspberry pi?

I am attempting to build a node.js application on a Raspberry Pi which can communicate with a remote socket.io server.
The socket.io server quite simply writes to the console when a new connection is established and when an existing connection is closed.
The socket.io client works as expected when run in a browser.
However, when I run the client code from a Raspberry Pi it connects and immediately terminates. This does not allow me to perform any function such as emitting or receiving.
The on connect event is never fired.
var io = require('/usr/local/lib/node_modules/socket.io-client');
var serverUrl = 'http://remoteserver.com';
console.log('Connecting to ' + serverUrl);
var socket = io.connect(serverUrl);
socket.on('connect', function(socket) {
console.log('Connection established!');
console.log(socket.id);
socket.on('disconnect', function() {
console.log('Disconnected from server');
});
});
The code above will output:
Connecting to: http://remoteserver.com
On the server side, the output will show a new connection and eventually a timeout close.
Why is the client on connect event not firing? How can I persist this connection so that I can eventually send inputs to the server?
Remove the line:
socket.close();
from your code. You are closing the socket immediately. Remember that all the event handlers are asynchronous. They are non-blocking and will be called some time in the future. Meanwhile, the rest of your code runs to completion and thus your socket.close() is executed before your client has any chance to get any events (other than the disconnect event).
If you want to do some stuff and then close the socket, then you need to close the socket only from some event handler that indicates that your operation is complete and you are now done with the socket.
You only need to call socket.close() when you want to close the connection from the raspberry pi. Also, the socket.io-client documentation does not use the .connect method, but instead calls require('socket.io-client')(serverUrl)
var io = require('/usr/local/lib/node_modules/socket.io-client');
var serverUrl = 'http://remoteserver.com';
console.log('Connecting to ' + serverUrl);
var socket = io(serverUrl);
socket.on('connect', function(socket) {
console.log('Connection established!');
console.log(socket.id);
});
socket.on('disconnect', function() {
console.log('Disconnected from server');
});
//Removed the socket.close() line

What is .on function of socket in tcp connection in Node Js

I have a quick question. Can anyone explain this
socket.on("message",function(message){})
I am trying to connect to TCP server on node.js
server.on('connection',function(socket){
socket.on('message',function(message){
console.log("got the message");
socket.sendEndMessage("hello");
}
);
} );
I need to know when socket.on("message",function(message){}) will be called.
socket.on("message",function(message){}) will be called when a socket connected to the server emits a 'message' event:
socket.emit('message', { /* an object to be sent */ });
Using socket.on method, allows you to manage how a custom or built-in received message event will be handled. If you're sending different kind of messages through the server, lets say, requestsStats and requestUsersList message types, you'll be emitting messages like
socket.emit('requestStats', { filter: statsFilter });
socket.emit('requestUsersList', { filter: userAccessLevel });
you'll need to process them on the server (or clients) using:
socket.on('requestStats', function(message){ // process message content });
and
socket.on('requestUsersList', function(message) { // process message content });
Basically, you can define custom events/messages to be sent through web sockets.

socket.io not reconnecting after a disconnect

I am developing a node.js application using socket.io to communicate between server and client. If the server faces any error, I send an error message to the client and I close the connection from both server and client. However when the client tries to reconnect, it is no longer able to connect to the server. My code
server.js
io.sockets.on('connection', function(socket) {
/*Some code*/
stream.on('error',function(errormsg){
socket.emit('error',{txt: "Error!"});
socket.disconnect();
});
});
client.js
var server_name = "http://127.0.0.1:5000/";
var socket = io.connect(server_name);
socket.on('error',function(data){
console.log(data.txt);
socket.disconnect();
});
function submitclick()
{
var text="hello";
if(socket.connected ==false)
socket= io.connect({'forceNew': true});
console.log(socket.connected);
}
Status of socket.connected is false. I do not receive it on the server side either.
I don't think your call to io.conncet is synchronous, you're checking socket.connected too early. If you want to verify that your reconnect succeeds, try it like this:
function submitclick()
{
var text="hello";
if(socket.connected ==false) {
socket= io.connect({'forceNew': true});
socket.on('connect', function() {
console.log('Connected!');
});
}
}
Edit:
As #jfriend00 points out there's probably no need for you to do the socket.disconnect() in the first place as socket.io should automatically be handling reconnection.

Why don't I see a response from socket.io-client with node.js?

var io = require('socket.io-client'),
socket = io.connect('targeturl', {
port: 8080
});
socket.on('connect', function () {
console.log("socket connected"); //this is printed.
});
socket.emit('list', {"user":'username',"token": 'mytoken'});
socket.on('message', function(data){
console.log(data);
});
socket.on('error', function(data){
console.log(data); //nothing is printed
});
I see the message 'socket connected' when running this from node.js on the command line but I don't see a response from the 'list' call.
Note that this is a specific question about using socket-io-client from Node.js as a command line application.
I have verified using curl that I can reach the socket server which is REMOTE i.e I do not have the server code but I know that it uses socket.io.
I'm no expert on the matter, but it appears you're attempting to emit the message before the connection is established. (This stuff is asynchronous after all.)
Try moving the emit call inside of the handler for the 'connect' event, to ensure that it happens afterward.

How to call a function when node server is up?

I want to call a function when the net.serverCreate is up. It need to call this function when the server is started and not when a new connection appears. Event 'listening' dont fire...When I start the server I want to check something in Mysql data-base... How to execute functions when server starts?
My app:
var server = net.createServer(function (socket) {
socket.on('listening', function () {
console.log("Console is listening! "); //Its dont log
});
socket.on('data', function (message) {
});
socket.on('end', function () {
socket.end();
});
});
server.listen(1337,function(){
console.log("Server starts succefully"); //Its working!
});
Event 'listening' dont fire
The callback to createServer is handed a client Socket. Client-side sockets don't listen for requests; they make requests. So a listening event is never emitted by Sockets
On the other hand, net.createServer() returns a server-side socket(similar to Java's ServerSocket)
This should work.
server.listen(1337,function(){
//mysql db query
});
The callback to listen is executed when the server is bound to the specified port, i.e., when the server starts listening. The last parameter to listen is added as a listener for the listening event.
Another way to monitor the server-start event is:
server.on('listening', function() {
//mysql db query
});
Listening event

Categories

Resources