Using socket.io from a module - node.js

My sio = require('socket.io').listen(app) is in my server.js file, but I'm calling a method in a library that would like to push a message to the client... say api.user.pushToClient()
How am I able to access sio.sockets from there? Perhaps my structure is incorrect?
Folder structure:
server.js
api
|--user.js
|--another.js

in server.js append this line
module.exports.sio = sio;
in api/user.js
sio = require('../server').sio;
sio.sockets.on ...
Or did I misunderstand the question?

What I understood from the question is you want to know how to use socketIO with node module.Based on my understanding you can use it as below:
First install socketIO module locally with npm by running " $npm install socket.io " command for windows.
Add Script to your HTML page:
<script src="/socket.io/socket.io.js"></script>
Now add var io = require('socket.io'); to your server or js file where you are going to use it.
Then you can have server startup code listen to that server and on connection of it perform the options for any event.
var listener = io.listen(server);
listener.sockets.on('connection', function(socket) {
socket.on('locationClick', function(data) {
// perform the function on receving locationClick event.
}
}

Related

How can resolve **Uncaught Reference Error: io is not defined at client.js:1:16** error?

I am trying to create a real time chat app project using node and socket but when I try to run this using nodemon then it gives me error like
Uncaught ReferenceError: io is not defined
at client.js:1:16
and
GET http://localhost:3000/socket.io/socket.io.js net::ERR_ABORTED 404 (Not Found)
plz help me to get out from this frustration.
here are respective code:-
const express=require("express");
const http=require("http");
const app=express();
const server=http.createServer(app);
const io=require("socket.io")(server)
app.get("/",function (req,res) {
res.sendFile(__dirname+"/index.html");
})
app.use(express.static(__dirname+"/public"))
io.on("connection",(socket)=> {
console.log('Connected');
})
app.listen(process.env.PORT || 3000,function(){
console.log('Running....');
})
code at client.js:-
const socket = io()
let name;
let textarea=document.querySelector("#textarea");
let msgArea=document.querySelector(".mssg_area");
do{
name = prompt("what do your friends call you?");
}while(!name);
textarea.addEventListener("keyup",function (e) {
if(e.key==="Enter"){
sendMessage(e.target.value);
}
})
function sendMessage(message) {
let msg={
user:name,
message:message
}
appendMessage(msg,"outgoing")
}
function appendMessage(msg,type) {
let mainDiv=document.createElement("div")
let className=type
mainDiv.classList.add(className,"message")
let markUp=`
<h4>${msg.user}</h4>
<p>${msg.message}</p>
`
mainDiv.innerHTML=markUp
msgArea.appendChild(mainDiv)
}
It would be very helpful to me if you resolve this issue. Thank you in advance!!
on the client side you should install socket.io-client not socket.io
Client Api
Be sure, you have installed socket.io module. If not installed, install this by using command -
npm install socket.io
I had been fiddling around with this kind of problem for weeks. I was not able to solve this problem and it had been stressing me out. But Alas, I finally found the solution by searching in several sources. So I am going to tell the step by step process on how to fix it.
First and foremost, install the socket.io package by doing in terminal (npm install socket.io)
Second, type npm install nodemon
Third, type npm init --yto get the file package.json. Then, in the package.json, at "scripts": {}, write "devStart": "nodemon server.js" (so you don't have to re-run the code in the server) and also "start": "node server.js". Then, at "main": , type "main": "server.js"
Now, in your script.js, you forgot to put the link in io() as an argument.
For instance, you can do:
const socket = io('http://localhost:3000'); //You need to pass in the localhost:3000
let name;
let textarea=document.querySelector("#textarea");
let msgArea=document.querySelector(".mssg_area");
do{
name = prompt("what do your friends call you?");
}while(!name);
This will tell the server to access the webpage in localhost:3000
Then, in the server.js, import the module socket.io by doing:
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
which you did correctly.
But, in the last part of your code, you should do:
server.listen(process.env.PORT || 3000,function(){
console.log('Running....');
})
instead of: app.listen()
Now, this is the most confusing part. This is where the error kicks in. The reason why we get the Error:
Uncaught ReferenceError: io is not defined
at client.js:1:16
is because we haven't imported/require the module for the socket.io in the client.js. In order to do that, we first need to get the module from the node_modules folder. So:
Scroll and Find the socket.io module in the node_modules folder in VSCode ( you should see socket.io in it)
Make a new folder in your directory/folder that has your client.js and server.js called public
Then copy or move the file/module to the new folder public
Now, go to your HTML file and in the <body> type the following:
<body>
<script src="public/socket.io/client-dist/socket.io.js"></script>
<script src="client.js"></script>
</body>
Now, I might be wrong here since people do the other way that is(Doesn't work for me and probably you):
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
<script src="client.js"></script>
which, in my case, doesn't work for me because there is no such socket.io module in localhost/website. But, it probably doesn't work for me since I am using windows. So, if the first <script> tag I gave you didn't work, then you can try this one.
The point what I'm trying to tell you is, you need to import/require the socket.io module for the client.js in order for it to work. Otherwise, it will give that Unreferenced Error. Doing const io = require("socket.io") in client-side javascript won't work. You have to import it using <script> tag in the body. Or by doing <script defer src="..."> in the head.
So after all of this, it should work. Go to your server.js and run the server at localhost:3000. Go to Chrome(or other sites) and type localhost:3000
If the error is still there, then maybe the path to your public folder with the socket.io module is wrong OR I am wrong.
If you get the CORS error:
const io = require('socket.io')(server, {
cors: {
origin, "*" //Or type your localhost or link
methods: ["GET", "POST"]
}
});
you can go to info on socket.io Cors for more info.
Or install the cors module by doing npm install cors
Apologies if I did something wrong or for my broken English. I am terribly sorry as this is my first ever StackOverFlow answer and I couldn't just let this question go to rest. I must answer as I have the viable solution for it. So Thanks for reading this.

socket.io/socket.io.js cannot be found

I have this socket server:
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
...
app.listen(3001);
Express and socket versions:
"express": "^4.16.3",
"socket.io": "^2.1.1"
And I call this on client side:
<script src="http://localhost:3001/socket.io/socket.io.js"></script>
When I run socket server and open client app on chrome, I get this message: "Failed to load resource: the server responded with a status of 404 (Not Found)".
I don't intent to copy socket.io.js to a public folder as it's not the right way to do it according to socket.io docs.
That said, what am I doing wrong?
Possible fixes:
Make sure you run npm install and you don't have errors or incomplete installations:
inside your project's directory, go to ./node_modules/socket.io/node_modules/socket.io-client/dist and copy the file named socket.io.js and put it into one of your static or resources directory.
Don't forget put the following line to serve static files, now you should be able to browse it under: http://localhost:3000/resources/socket.io/socket.io.js
app.use('/resources', express.static('resources'));
If not fixed, here is a complete basic example follow the steps below.
Copy paste the following into a file myfile.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
http.listen(3000, function(){
console.log('listening on *:3000');
});
Run the following commands:
$ npm i express --save
$ npm i socket.io --save
$ node myfile.js
Open your browser http://localhost:3000/socket.io/socket.io.js

socket.io including in project and installation

Im want to include socket.io in my project. I installed it using npm install -g socket.io still being in directory my files to the project are located in.
I created script to test if it was successfull
i creater server.js with code
var client=require("socket.io").listen(8080).sockets;
client.on("connection",function(socket){
console.log("Someone has connected")
})
and included in html file
<script type="text/javascript" src="http://127.0.0.1:8080/socket.io/socket.io.js"></script>
I tried to run node server.js to see if there will be message in console but there wasnt , . Whad did i do wrong? I a trying to solve this problem but can find solution. Thanks for helping.
You must initialize a connection in html file (on client side).
If you are trying to connect to the host that serves the page you can use:
var socket = io();
or specify address:
var socket = io.connect('http://127.0.0.1:8080');

Localhost not working with node.js and socket.io

I am trying to learn the basics of node.js and socket.io. I have been using this tutorial http://tutorialzine.com/2012/08/nodejs-drawing-game/
the full code for this problem can be seen in the link above.
I can create a basic web server with node.js and get it to return hello world so I am sure that's installed correctly. However upon installing these packages
npm install socket.io#0.9.10 node-static
and setting up the serverside js as instructed
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
nstatic = require('node-static');
var fileServer = new nstatic.Server('./');
app.listen(8080);
I just get this prompt in my cmd and a constantly hanging web browser, instead of the html page that is meant to be served.I think I may have messed up an install but upon looking at the list of installed packages in npm it states both socket.io and node-static are present.
The code below should be more effective?, it looks like you are missing the handler part. The response must be explicitly ended or browser requests will hang forever like you are seeing. The node-static file.serve method manages the request once you pass it down. The source for .serve is here: https://github.com/cloudhead/node-static/blob/master/lib/node-static.js#L164
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
nstatic = require('node-static');
app.listen(8080);
var file = new nstatic.Server('./');
function handler(request, response) {
request.addListener('end', function () {
file.serve(request, response);
}).resume();
}
console.log('started')
Note also that the default file to serve to responses at / is index.html.

Node.js restify with socket.io

Is it possible to run socket.io & restify on the same port like express & socket.io?
I did just like this but it didn't work
# server.coffee
restify = require 'restify'
socket = require 'socket.io'
server = restify.createServer()
io = socket.listen server
server.listen 1337
when I try to connect to socket.io:
GET http://localhost:1337/socket.io/socket.io.js 404 (Not Found)
As suggested here by #jtomasrl and #zacheryph, this worked for me:
var server = restify.createServer();
var io = socketio.listen(server.server); //Note server.server instead of just server
Since this is the first google hit for "restify socket.io" I'm posting a new answer. This works fine now as documented at http://restify.com/docs/home/#socketio
Apparently, using socket.io with restify is not possible yet: https://github.com/mcavage/node-restify/issues/230

Resources