Socket.io and Express not sending data - javascript

I'm trying to use socket.io to connect to this websocket api:
https://www.cryptocompare.com/api/#-api-web-socket-
(wss://streamer.cryptocompare.com)
I guess im not really understanding socket.io very much.
I created a blank html document:
<!doctype html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.slim.js"></script>
</head>
<body>
<div id="data-show">
</div>
<button id="connect-sock">Connect</button>
<button id="disconnect-sock">DISConnect</button>
</body>
<script src="index.js"></script>
</html>
index.js:
var socket = io('wss://streamer.cryptocompare.com')
console.log('connected')
var btn = document.getElementById('connect-sock')
var btn2 = document.getElementById('disconnect-sock')
var show = document.getElementById('data-show')
//I also tried adding an event listener to a button so when i clicked it, it would do this:
socket.emit('SubAdd', { subs: ['0~Poloniex~BTC~USD'] } )
//Same result of nothing.
socket.on('SubAdd', function(data){
console.log(data)
})
server.js:
var express = require('express')
var socket = require('socket.io')
var app = express()
var server = app.listen(4000, function(){
console.log("well met")
})
app.use(express.static('public'))
var io = socket(server)
io.on('connection', function(socket){
console.log('well met from socket connection', socket.id)
})
server.js is in a file named 'socket-test'. index.html and index.js are in 'socket-test/public/'
so for some reason, in server.js, socket.id will not log to console. its as if this function is being skipped over. but when i change the address in index.js to http://localhost:4000, i get socket.id in console... not sure whats going on there.
Edit: I rarely get socket id when using the wss://streamer.cryptocompare.com/ , sometimes I do, most of the time i dont. It usually works when I switch to localhost, run the server, stop the server, then switch back to the streamer, but if i reload, i dont get socket.id anymore.
I thought that all I was asking it to do here was emit subs to wss://streamer.cryptocompare then console.log(data) that it returns after emitting the subs.
am I missing something here?
Sorry in advance if its blatantly obvious that I'm missing something. I've only known about socket.io for maybe 3 days now, and only today have I watched a basic tutorial on youtube.

You don't need the Express code because in this case the server you want to talk to is on the cryptocompare server -- not a local server. This is captured in your code when you initialize the io object in the HTML file.
Of course, you could still use Node to talk to the cryptocompare websockets API if you're more comfortable with Node. But then you wouldn't need the in-browser JavaScript. Either way, what you need is to create some kind of client in any runtime that speaks websockets and can talk to the cryptocompare websockets API.
With regard to the code being skipped over -- you're right! It is. socket.io is an event driven WebSockets framework. This means that clients register their interest in certain kinds of events/messages, and when those are triggered special functions known as callbacks are called.
If it helps, you can think of those events like channels in a chat room -- if you're not in the right room, you won't see the messages for that room. So you'll need to know what messages you should be listening for, register your interest in those, and register callback functions for each one.
Thankfully cryptocompare has provided client code examples that should help you get an idea for the kinds of messages you should be listening for.
See here

Related

how to emit event on nuxt-socket.io from client to server

im learning to use Nuxt in the past i have worked with socket.io and vue but this time i am using nuxt-socket-io
https://nuxt-socket-io.netlify.app/
My problem is that I cannot send events from client to server
here an example:
in socket-io-server.js
io.emit ("eventTry")
at homepage.vue
mounted () {
this.socket = this. $ nuxtSocket ({
name: "main",
});
this.socket.on ("eventTry", () => {
console.log ("this Work Good");
})
},
and this works fine
but when I try to send from the client to the server nothing works example:
at homepage.vue
this.socket.emit ("eventTryClient");
and in socket-io-serve.js:
io.on ("eventTryClient", () => {
console.log ("something should happen here")
})
and this DONT WORK
I've really looked everywhere and I can't find a solution to this problem that should be so simple, could someone help me? I need to have a bidirectional communication, which is the best of socket.io I think
Thanks in advance for your help <3
You need to listen for events on the socket. Listening on a namespace, e.g. your io variable, won't actually listen to events sent by the client. More info here, although it doesn't explicitly state to listen on the client socket.
I do not know where I saw this solution, but I will share it because surely there is someone else who is interested in this... The only thing necessary to establish the connection between client and server is the following:
in your client (example homepage.vue):
import io from "socket.io-client";
const ioClient = io.connect("http://localhost:3001"); // replace it with the url of your socket
The URL it's in nuxt.config.js, and you probably have something like this:
// socket.io configuration
io: {
sockets: [{
default: true, // make this the default socket
name: 'main', // give it a name that we can later use to choose this socket in the .vue file
url: 'http://localhost:3001' // URL wherever your socket IO server runs
}]
},
With this you can use ioClient as your connection on the client for example:
ioClient.on("connect", () => {
console.log("socket-io-client conected")
ioClient.emit('chatmessage', this.message); //now this works and you can receive it on your server normally
})
I dont know if this is the better way to do that, but i dont really saw solutions for this in the documentation ... maybe im blind, or no body answer that

Non Existent Clients Connecting To Socket.io

Im creating a realtime application using socket.io and its been going alright, until i found somthing strange going on when a client connects to the server. The client will connect, and the connection event will properly reflect on the server, but shortly after, a cluster of what i can only describe as "fake clients" start connecting to the server and triggering the connection event a seemingly random number of times. These strange connections that come out of nowhere are causing an increasingly big delay on the servers response to actual clients as more start to join. I created an extreamly basic socket.io boilerplate just to see if the strange bug would persist without all the complexity of my application, and to my suprise it did, and i cant understand why. Any info will be greatly appriciated. Here is my basic server and client setup -
const http = require("http");
const fs = require("fs");
const server = http.createServer();
const io = require("socket.io")(server);
io.on("connection",() => {
console.log("A client has connected!");
});
server.on("request",(req,res) => {
fs.readFile("./index.html",(err,data) => {
if (!err && data) {
res.writeHead(200,{"Content-Type": "text/html"});
res.end(data);
} else {
res.writeHead(500);
res.end();
}
});
});
server.listen(3000,() => {
console.log("Server is active...");
});
note how i am logging that a client connected each time the connection event is triggered. Here is the index.html file and client script -
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.socket.io/3.1.1/socket.io.min.js" integrity=" sha384- gDaozqUvc4HTgo8iZjwth73C6dDDeOJsAgpxBcMpZYztUfjHXpzrpdrHRdVp8ySO " crossorigin="anonymous"></script>
<script type="text/javascript">
const socket = io({autoConnect: false});
socket.connect();
</script>
</head>
<body>
</body>
</html>
Here is the console output i get when i connected a single client to the server. Again, its seemingly random each time.
A client has connected
A client has connected
A client has connected
A client has connected
A client has connected
The first one is genuine, but i have no idea where the rest come from, as they even have a different socket id when i tried to log it out. Any type of feedback is appriciated.

socket.io - socket is not defined on client only

I'm running two instances of socket.io on my local machine (two namespaces). The present issue is that when trying to connect from the client side (to any namespace), I get the following error:
Uncaught ReferenceError: socket is not defined
I tested this without custom namespaces and the same issue arose. The server side is just fine as I can emit events.
The Client code looks like this:
Client
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js"></script>
<script>
var socketOptions = {};
socketOptions.transports = ['polling'];
var client = new PlayClient();
var playSocket = io.connect('http://localhost:8044/clients', socketOptions);
playSocket.on('connect', function(socket) {
console.clear();
console.info("CLIENT: Connected.");
socket.on("client:change scene", function(newSceneId) {
console.log(newSceneId);
client.changeScene(newSceneId);
});
});
</script>
It looks like I just overwrote the socket. So, basic troubleshooting led me to this answer leading me to confirm that. However, passing (data) or something else instead still leaves socket undefined but with the console declaring: TypeError: undefined.
If I change .on('connect') to .on('connection'), the socket is no longer overwritten but fails to connect or receive any emitted events because the socket.io client does not understand the 'connection' event.
Any help with this is much appreciated, as I seem to be caught in a circular rut.
you seem to be confusing server side and client side events; they are pretty different. each client object can only be connected to a single server, while the server can receive many connections
maybe try something like:
var playSocket = io.connect('http://localhost:8044/clients', socketOptions);
playSocket.on('connect', function() {
console.clear();
console.info("CLIENT: Connected.");
}
playSocket.on("client:change scene", function(newSceneId) {
console.log(newSceneId);
client.changeScene(newSceneId);
});

Is it possible to create a "fake" socket connection to a nodejs server that is secured through SSL?

I'm using socket.io-client to create a socket connection to my locally-running server. See my code below:
// Working example of connecting to a local server that is not SSL protected
var io = require('socket.io-client')
var socket = io.connect('http://localhost:3000', {reconnect: true});
socket.on('connect', function(){ console.log("inside 'connect'") } );
socket.on('connection', function(){ console.log("inside 'connection'") } );
socket.on('event', function(data){ console.log("inside 'event'") } );
socket.on('disconnect', function(){ console.log("inside 'disconnect'") } );
var payload = {email: 'fake#gmail.com', password: 'tester'};
var tokens = {browserId: 'b965e554-b4d2-5d53-fd69-b2ca5483537a'};
socket.emit("publish", {logic:"user", method:"signIn"}, payload, tokens, function(err, creds) {
console.log("inside the socket client emit callback. err: " + err);
console.log("creds: " + creds);
});
Now for my problem. As I stated in the comment at the top of that code, I can connect to my local nodejs server and get the response I expect when I turn off SSL encryption on my server. As soon as I turn SSL on, I stop getting any response at all from the code above. I don't see any message in my server logs or from the command line, where I'm running the code above with node.
My goal is to be able to run the code above, with SSL turned on in my server, and get the same response that I get when SSL is turned off. I've tried a bunch of variations on the code I included above, such as:
connecting to "https://localhost:3000"
connecting to "//localhost:3000"
connecting to "https://localhost:3443" (this is the port I have to connect to when I have the nodejs server running with SSL)
changing {reconnect:true} to {reconnect:true,secure:true}
I'm truly stumped, and I've been doing a bunch of research on the web and on my node server. It's my company's code and I didn't originally implement the SSL components, so I've spent a few hours looking at our code and trying to understand how adding SSL changes everything. I'm also a student and have about 2 years of experience behind me, so I'm good but I'm no expert. Have I said anything above that indicates if my task is impossible to achieve, or if maybe I have just overlooked something? Any leads on things to check out would be appreciated :)

Socket.io middlewhere functions

I am trying to seperate logic in my socket.io server but i am experiance some issues.
say for instance i have the following:
io.on('connection', function (socket) {
var fileModule = require('./costum_modules/FileModule.js')(io);
app.use(fileModule);
});
Now inside the fileModule i have the following code:
var fileModule = function (socket) {
socket.on('userData', function(msg){
var i = 0;
});
}
module.exports = new fileModule();
Sadly the socket i undefined.
My question is can i do it like this or is it not possible to pass a singleton to another file and make it read from the same object?
You can use other files to break up your logic, but there are a couple issues with your code.
First, I think Hacketo is correct that you don't want to do new fileModule(), just:
module.exports = fileModule;
Second, when call require, you are passing the global socketIO object (io). You should pass it the socket you get in the connection handler. E.g.
require('./costum_modules/FileModule.js')(socket);
I think that will work to move some of your socket.io message handling code into a module. Now your socket will respond to userData messages from a client. However, unless you have some custom application, I don't think app.use is going to do what you expect. You can't hook web socket handlers into an Express/Restify/Connect/Whatever middleware chain. But you could write a middleware that sends a message to your socket server.
If you are just trying to share the session between your app and socket server, try this SO answer.

Categories

Resources