Socket.io - Stop listening event client-side - socket.io

Im trying to stop listening to an event (Client-side) on socket.io, I'm using this to listen to the event:
function connectWebSocket(channel){
var socket = io('https://mywebsite.com:3000');
socket.on('connect', () =>{
console.log('connected');
socket.on('test', function(data) {
alert('event call');
});
});
}
It works ok, but how i stop listening to the event 'test'?
I tried:
socket.off('test');
also tried:
socket.removeAllListeners('test);
and a lot of more commands, but nothing seems to work, as i started listening client-side, how i stop listening client-side?

Related

how to listen for all active websockets messages in javascript

hey guys so i have this email provider called https://emailfake.com/channel6/ i want a script that will listen for all ws comming messages for already opened connections
const socket = new WebSocket('wss://emailfake.com');
// Listen for messages
socket.addEventListener('message', (event) => {
console.log('Message from server ', event.data);
});
note : a script that will work on console of devtools

Socket.emit() outside socket.on()

Do we always have to use socket.emit() inside a socket.on() like that:
io.sockets.on('connection', function (socket) {
console.log('User connected !');
retrieveDictionnary((dictionnary) =>{
socket.emit('dictionnarySend', dictionnary);
}
}
I want to create on my client side a function which ask information to the server when I click on a button:
translateServer(parameter, control){
this.socket.emit('translate', [parameter,control]);
}
But it seems that it's not working, the server never receive this message.
Thank you !
The pattern you are using above is the recommended way of interacting with a socket (ie acquiring a socket instance when the 'connection' event fires, and then calling emit() from that socket instance, etc).
If I understand your client-side requirements correctly, you are wanting to send data to the server via web sockets - are you sure the socket that you have established a web socket connection between the client and server?
For instance, if you add the following to your client-side code, you should see a success message in your console:
const socket = io.connect('YOUR SERVER ADDRESS');
socket.on('connect', () => {
console.log('connected to server!');
// [UPDATE]
// This assumes you have a <button> element on your page. When
// clicked, a message will be sent to the server via sockets
document.querySelector('button').addEventListener('click', (event) => {
// Prevent button click reloading page
event.preventDefault();
// Send message to server via socket
socket.emit('MESSAGE_ID', 'test message from client' + new Date());
});
});
Update
This shows your original server code, expanded with the detail needed to receive and print data sent from client via sockets:
io.sockets.on('connection', function (socket) {
console.log('User connected !');
// Register a server handler for any messages from client on MESSAGE_ID channel
socket.on('MESSAGE_ID', (message) => {
// Print the message received from client in console
console.log('message from client', message);
})
retrieveDictionnary((dictionnary) =>{
socket.emit('dictionnarySend', dictionnary);
}
}

socket.io connection event not firing in firefox

Im having something like the below code.
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost:8080');
socket.on('connect', function(){
socket.on('some-event', function(data) {});
});
socket.on('disconnect', function(){});
</script>
Inside the connect callback I have some code that responds to messages. This works perfectly fine on chrome. On first page load it works fine on firefox. If you reload the page then the connect event does not get called.
Im using 1.4.8 version of server and js client
I solved it using the following code. Not very clean but for the time being this helped us to progress with the project. As you can see the problem is the connect event not firing after a page reload, so I decided to attach the events after a timeout if connect was never fired.
function attachEventListners() {
socket.on('some-event', function(data) {});
}
var attached = false;
socket.on('connect', function(){
attachEventListners();
attached = true;
});
setTimeout(function() {
if (!attached) {
attachEventListners();
}
}, 1000);
You don't have to declare event listeners inside a connect listener, so even though I don't know a direct solution to your problem, I think this'll work around it:
<script>
var socket = io('http://localhost:8080');
socket.on('some-event', function(data) {});
socket.on('disconnect', function(){});
</script>
Because being able to receive messages implies that the socket is connected.
Instead of a timeout, you should use the load event listener on window
window.addEventListener("load",attachEventListners);

Is it possible to use socket.io server with pure html5 websockets?

I want to use sockets in my web app. I don't want to use socket.io library on client-side. It's OK for server-side though. Can I do this?
Now with socket.io on server and pure websocket on client I have destroying non-socket.io upgrade error. I've googled that it means that I have to use socket.io-client library on client-side. Is there any way to avoid that? I don't want client to be tight with this library and use pure html5 websocket instead.
If it's not possible what should I use for server to connect with pure html5 websockets?
If someone is curious here is my server code (coffeescript file)
# Require HTTP module (to start server) and Socket.IO
http = require 'http'
io = require 'socket.io'
# Start the server at port 8080
server = http.createServer (req, res) ->
# Send HTML headers and message
res.writeHead 200, { 'Content-Type': 'text/html' }
res.end "<h1>Hello from server!</h1>"
server.listen 8080
# Create a Socket.IO instance, passing it our server
socket = io.listen server
# Add a connect listener
socket.on 'connection', (client) ->
# Create periodical which ends a message to the client every 5 seconds
interval = setInterval ->
client.send "This is a message from the server! #{new Date().getTime()}"
, 5000
# Success! Now listen to messages to be received
client.on 'message', (event) ->
console.log 'Received message from client!', event
client.on 'disconnect', ->
clearInterval interval
console.log 'Server has disconnected'
And here is a client-side
<script>
// Create a socket instance
socket = new WebSocket('ws://myservername:8080');
// Open the socket
socket.onopen = function (event) {
console.log('Socket opened on client side', event);
// Listen for messages
socket.onmessage = function (event) {
console.log('Client received a message', event);
};
// Listen for socket closes
socket.onclose = function (event) {
console.log('Client notified socket has closed', event);
};
};
</script>
I've found this library, seems OK for my needs https://npmjs.org/package/ws

Is there a callback for the io.connect() method in Socket.IO?

Is there any callback for the io.connect() method on the client side? I would like to print some text about connection failure, otherwise proceed normally with the site's socket interactions.
Sure, checkout the documentation for Socket.IO-client with the examples there:
https://github.com/LearnBoost/socket.io-client#sockets-for-the-rest-of-us
socket.on('connect', function () {
// socket connected
});
In the current release of socket.io (1.3.x) you can use the connect_error event or the reconnect_failed event:
var socket = io(serverUrl);
socket.on('connect_error', function() {
console.log('Connection failed');
});
socket.on('reconnect_failed', function() {
console.log('Reconnection failed');
});
See: https://github.com/Automattic/socket.io-client#events

Resources