I'm working on a project which consists in creating a game of the goose like. In order to do that, I'm using Node.js, Express, jade and now Socket.io. But I encounter some trouble, like, in example, to share the position of one client to the other client. Because my variable position is in a function in index.js and I don't know how I can use Socket.io in a route file. I try some things, but nothing works.
On internet, I've seen some people who say that there is no-sense to use Socket.io in an express route file. So how can I do that ?
In my index.js I've that :
exports.deplacement = function(io)
{
return function(req,res)
{
//[...]
io.sockets.on('connection', function(socket)
{
socket.broadcast.emit('position', space);
});
res.render('moteur' //[...]);
}
}
And in my moteur.jade I've done this :
script(src="/socket.io/socket.io.js")
script.
var socket = io.connect('http://localhost:3000');
socket.on('position ', function(space) {
alert(space);
})
First of all, I'm not sure what your question exactly means, but if it is what I think it is then I think what you mean by using socket.io in a route file is to be able to include the client side javascript lib provided with socket.io module of Node.
In order to do that, you have to allow the socket.io module to listen to server. This works like a middle-ware itself. Everything has to go through socket.io first before they are routed to the server. So, when you request the client side lib, it is uploaded to the client.
var express = require('express')
, routes = require('./routes')
, http = require('http');
var app = express();
var server = app.listen(3000);
var io = require('socket.io').listen(server)
Related
I am just learning webdev and want to try to make a multiplayer game using Express and socket.io
I can make a server with socket.io in it which listens. That part works fine.
However when I try to connect a client, this only works if I let the HTML file with the following in it be served by the server like follows:
Server code:
const express = require('express')
const app = express()
const http = require('http')
const server = http.createServer(app)
const { Server } = require('socket.io')
const io = new Server(server)
const port = 3000
io.on('connection', (sock) => {
console.log('client connected')
})
// This seems to be necessary, but I don't want it to be!!!
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html')
})
server.listen(port, () => {
console.log(`Server listening on port ${port}`)
})
This index.html has the following at the bottom:
<script src="/socket.io/socket.io.js"></script>
<script>const socket = io()</script>
However I want to keep all my frontend code seperate from the server. I made a seperate repository for the frontend and backend. I want the frontend to contain all the UI logic and use only data calls (AJAX) to get Json data from the server. So I want to put this index.html file in my frontend code only.
Yet if I do this the connection doesn't work.
I can start the server fine.
I open index.html from WebStorm which also creates a server for this which I configured to also listen to port 3000
Yet it cannot find /socket.io/socket.io.js and I get the following error in the console.
It also doesn't work if WebStorm runs on a different port.
The resource from “http://localhost:3000/socket.io/socket.io.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff).
How can I keep this html in my client repo only and still work with socket.io, or is this not possible?
You can't have multiple servers listening on the same port. Run the servers on different ports and either:
Have a reverse proxy forwarding requests to your Socket.io server (which needs special handling) and your front end server or
Put an absolute URL in the script src and configure CORS.
I am new to SocketIO, I have referred many blogs and documentation for socket and everywhere we first need to create an HTTP server and then attach the socket to it like this -
var app = express();
var httpServer = http.createServer(app);
var io = socketio.listen(httpServer);
What does the second line mean? why are we creating one extra HTTP server while express(web framework) is already defined?
Because I never created a new HTTP instance for my RESTful application, I simply listened to express instance like this -
var express = require('express');
var app = express();
app.listen(8000);
Thanks in advance!
If you want socket.io to run on the same port as your web server, then you use the same server instance. If you want socket.io to run on a different port, then you create a new server instance on that port just for socket.io to use.
Socket.io works just fine using the same port and server instance as Express so unless you have a specific reason to run it on a different port, this is the usual way one would configure it.
Some code examples for socket.io show it in isolation by itself and thus they have to create an http server for it to use.
When using Express, you can get the server instance like this:
const express = require('express');
const socketio = require('socket.io');
const app = express();
const server = app.listen(8000);
const io = socketio(server);
My goal is this: JS but server-side. My solution, the obvious, node.js. I've used node.js quiet a bit. Mainly for an application, not a web server. The only reason I need to do server-side JS is that I need to use a library that connects to the Discord API. So I have a little test .js file with my node.js in it. It just prints text if it works. Basic. What I need it to do is whenever someone goes to https://example.com/something, it runs the node.js script and if the script ends up with printing "hello", then https://example.com/something will say "hello".
I've done some research on this, I've found ways to deploy a node.js app, which I know how to do. I can't really find anything that I'm looking for though.
You can use express to run a webserver on nodejs
Install express by running "npm install express" in your project folder through command prompt
Create a app.js file with the following code
var express = require('express'); // load the express library
var app = express(); // create an instance of express
var child_process = require('child_process'); //load the child_process module
app.get("/something", function(req, res) { // Setup a router which listens to the site http://localhost/something
child_process.fork("./yourCodeFile.js"); // Launch your code file
});
app.listen(80);
Run node app.js to listen to web connections
Then you put your code into the yourCodeFile.js which has to be be in the same folder as the app.js file, even better you could just write all your code in the app.js code as long as you keep it inside the function inside app.get
You should take a look at cloud-based lambda functions and platforms like AWS Lambda, which run a script in response to an HTTP request. They are relatively new and the architecture used to support this is being called "serverless", which is a simple term, albeit a bit of a misnomer. There are various tools out there to help you build these systems, such as the similarly named Serverless framework, though you can typically still use more traditional server frameworks that you are probably more comfortable with. Either way, you are not responsible for managing any server, including starting it or stopping it.
In terms of constructing a response that you are happy with, you can of course respond with any arbitrary string you want. See the AWS example of a Node.js handler.
exports.myHandler = function(event, context, callback) {
callback(null, "Hello, world!");
}
Lambda functions can also return binary data and work well with static storage systems like Amazon S3. For example, the function can be run in response to the creation of static assets.
Your code should look like this:
const http = require('http');
const url = require('url');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
const pathName =url.parse(req.url).pathname;
if (pathName == '/something') {
res.end('Hello World\n');
} else {
res.end('Please visit /something \n');
}
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
You should run your file with node youfile.js And when you do curl http://127.0.0.1:3000 you will see
Please visit /something
But when you do curl http://127.0.0.1:3000/something you will see
Hello World
I am pretty new to node.js and now I am doing a project on building a website on node.js. Sorry if my question is very naive.
I am using express framework.
My app.js is listening at port (3000).
In my route.js, I got some data from calling some API. I want to display the data to my datapoint.jade file. And because I want to draw those datapoint I have to embed a javascript file in jade. I want to use socket.io to achieve this sending and receiving data.
However, all the examples to construct socket is in app.js. I get data in router.js(in one of its callback function). app.js require router.js.
How can I send data from route.js to app.js and then send out to client side.
Could you please guide me some related and useful information? Or my design would not work at all?
A common paradigm is to pass any dependencies to your child modules:
// app.js
var socket = require('socket.io');
var app = require('express')();
var routes = require('./routes.js')(app, socket);
app.listen();
// routes.js
module.exports = function(app, socket){
var routes = {};
app.use('/', routes.handleIndex)
socket.on('connection', function(){
...
})
}
I wasn't sure if this is appropriate on the Ubuntu exchange or here but it is mostly code related i believe.
So I have created a neat working little web-chat application using socket.io which I've been developing on my Win10 pc using Git-bash and running it on my localhost with node.js and everything has been working just fine.
Thus I have come to a point where I would like to try out my app on my web-server.
Lets get more detailed what my Problems are:
I am unsure of how my server.js file should listen or open up the ports so to speak.
I have tried looking in the sockets.io chat example and tried their method yet the '../..' module leaves me confused.
Following the express.js site tutorial I actually get my server to respond listening on port 3000 yet my website returns the no socket.io/socket.io.js found.
this and this just lead to another localhost tutorial
In Short I have come to the point where when i do node server.js It seems to start listening here's the code to that part:
var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var port = process.env.PORT || 3000;
app.get ('/', function(req,res) {
res.sendFile(__dirname + '/index.html');
});
app.use("/static", express.static('./static/'));
server.listen(3000);
But now the problem is is that my html file cannot seem to find the socket.io/socket.io.js file, even though i have installed sockets.io, i consulted to this stack question which should fix it, but it didnt thus leads me to believe theres a thicker more server side issue?
Versions i am using:
express: **4.16.4**;
node : **10.15.0**;
npm : **6.4.1**;
socket : **2.2.0**;
EDIT: Added my html code snips
html
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script src="static/index.js"></script>