I'm in the process of learning Node and have a question I can't seem to find the answer to. In the following example of a minimalistic chat server the node server expects the client page to reside in the same directory as the server file, if I was building a client side app for a mobile device, how would I send the data back to the proper client?
var fs = require('fs')
, http = require('http')
, socketio = require('socket.io');
var server = http.createServer(function(req, res) {
res.writeHead(200, { 'Content-type': 'text/html'});
**res.end(fs.readFileSync(__dirname + '/index.html'));**
}).listen(8080, function() {
console.log('Listening at: http://localhost:8080');
});
socketio.listen(server).on('connection', function (socket) {
socket.on('message', function (msg) {
console.log('Message Received: ', msg);
socket.broadcast.emit('message', msg);
});
});
Are you running into this problem? If so, perhaps using the phonegap iOS / Android plugins for WebSockets may help you.
For reference, here is what res.end(fs.readFileSync(__dirname + '/index.html')); means:
Synchronously read the contents of the file index.html (located in the server's current directory)
End the HTTP response after sending the contents of the file over the network to the client who requested the page (could be the local machine, a phone, a computer on the internet -- anyone who has access to the server). In other words, node is acting as an HTTP server for the page index.html
Index.html presumably contains some socket-related code that instructs the client to connect to the socket on the server (the server's socket is created by socketio.listen(server))
Related
I am setting up a Client/Server communication between my tablet and my PC. My Client cant get any data from the server, what am I doing wrong.
My PC is running a Node.js server (using Express) and my tablet runs a client written in Node.js (using Express). I can access the server via the browser and get the data, but not through the javascript code.
My SERVER code is:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('App requested a connection');
});
app.listen(3000, () => console.log('Listening on port 3000!'));
app.get("/boxes", function (req, res)
{
//res.send(req.params[0]);
res.send("All boxes are in the basement");
});
My CLIENT code is:
const express = require('express');
const app = express();
console.log("Client working ...");
app.get("http://127.0.0.1:3000/boxes", function (req, res)
{
console.log("inside...");
console.log(res);
});
The CLIENT should return "All boxes are in the basement" and I get this when I use a browser but it doesn't work if I run the client code. The only message I get from client is "Client working ...".
Does anybody know what I am doing wrong?
Cheers
Express is a library for setting up and configuring an http server for incoming requests. It does not make outgoing requests to other servers. So, your client code is not a client at all.
Several problems here:
127.0.0.1 refers to your local device so your client is referring to itself when it uses 127.0.0.1.
In your client app.get("http://127.0.0.1:3000/boxes") is not a request for data. That attempts to set up an Express route for incoming requests as if you were declaring a second server. But, it's not even done correctly because you would only use the path there.
For a client to make a request of some other server, you would need to use a library call that actually does http requests. For example, you could do something like this:
Code:
const rp = require('request-promise');
rp.get("http://ipaddressOfServer:3000/boxes").then(data => {
// have response here
}).catch(err => {
// error here
});
I chose to use the request-promise library, but there are multiple different ways to make an http request. You can also use http.get() (lower level), request() (from the request library) or axios() from the axios library, etc...
Note, the computer your server is on (assuming it's running a desktop OS) will also have to probably turn of it's local firewall (e.g. windows firewall) or set up a specific rule to allow incoming connections on port 3000. Without that, the incoming connection will be blocked (for security reasons).
I created my Socket server with Express, SocketIO and Redis
server.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var redis = require('redis');
server.listen(8890, function (e) {
console.log(e);
});
io.on('connection', function (socket) {
console.log("new client connected");
var redisClient = redis.createClient();
redisClient.subscribe('message');
redisClient.on("message", function(channel, message) {
console.log("mew message in queue "+ message + "channel");
socket.emit(channel, message);
});
socket.on('disconnect', function() {
redisClient.quit();
});
socket.on('connect_error', function() {
redisClient.quit();
});
});
From command line, I run node server.js. Its worked.
I also created a html file to connect to that server.
From Browser Console, I run io.connect('http://localhost:8890'). I got as the result
As I see, too much connections (requests).
What happens? What wrong from my code?
You have mismatched client and server versions causing the initial connection to fail and the older client is dumb enough to just keep trying over and over again. If you are using 2.0.4 on the server, then you must use that version for the client too. If you serve the client version directly from your server with:
<script src="http://localhost:8890/socket.io/socket.io.js"></script>
Then, the socket.io server will automatically give you the right client version.
Or, you can manually link to the right version on your CDN such as https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js. But client and server versions MUST match.
The advantage of getting the client directly from your own server is that anytime you update your server version of socket.io, the client version will automatically be upgraded for you and kept in perfect sync since the matching client version is built into the server version.
I am new to node.js. I just installed node.js on my production server it was installed correctly and node.js is running on my putty cli the problem is I cannot access it on my browser. I think my problem is because I installed created my server on a subdirectory inside a subdomain e.g. subdomain.example.com here is my code
var http = require('http');
//create a server object:
http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
}).listen(3000); //the server object listens on port 8080
Now I am trying to access the node.js server by going to this address subdomain.example.com:3000 but I am getting no results. Please help Thanks!
I receive this error in console GET http://localhost/socket.io/socket.io.js 404 (Not Found). I used npm install to install express and socket.io. Everytime I try to access localhost:3000 it downloads a file instead of displaying chat.php
This is my javascript code
var express = require('express')
var app = express()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server);
server.listen(3000);
users = [];
connnection = [];
console.log('Server running!');
app.get('/',function(req, res){
res.sendFile(__dirname + '/game.php');
});
io.sockets.on('connection', function(socket){
connections.push(socket);
console.log('Connected: %s sockets connected', connections.length);
//Disconnect
socket.on('disconnect', function(data){
connections.splice(connections.indexOf(socket),1);
console.log('Disconnected: %s sockets connected', connections.length);
});
});
And this is what I added into php file
<script src="/socket.io/socket.io.js"></script>
<script>
$(function(){
var socket=io.connect();
});
</script>
res.sendFile(__dirname + '/game.php'); just sends a raw PHP file to the browser client. Instead, what you need to send to the browser is HTML. So, you either have to change your app to run in node.js and not PHP or you have to exec that PHP file and grab its output and send that to the browser.
Normally, if you wanted your page to be generated via PHP, you wouldn't be using node.js at all - you'd just be using PHP. If the only reason you brought node.js into the equation is because of socket.io, then maybe you should be using socket.io directly with PHP which you can read about in this question. You could use a hybrid of node.js and PHP, but it's unlikely to be all that efficient if you're using node.js to run your PHP. For that case, you would probably be better off running socket.io in node.js on a different port number, enabling cross origin access and just leaving your PHP to be PHP.
I found the working solution with PHP here https://github.com/jdutheil/nodePHP. I tested it and it is working just great.
I'm trying to do API in javascript for another users. I want to create a chat in realtime in Node.js with socket.io but I want to give the opportunity loading this API in common HTML through javascript. For example, if somebody copy and paste simple js script into your html, then chat is loaded.
My app is running in node on port 8080 and my other page is html on port 80.
How can I put node.js in other page?
below is my chat.js
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var cors = require('cors');
app.use(cors());
app.options('*', cors());
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
socket.on('chat message', function(msg){
console.log('the user wrote:' +msg);
io.emit('chat message', msg, id);
});
});
http.listen(8080, function(){
console.log('listening on *:8080');
});
In this way I try to load:
<script>
$.ajax({
xhrFields: {
withCredentials: true
},
dataType: "html",
url: "http://127.0.0.1:8080/index.js"
}).done(function(data){
// next function here;
});
</script>
You don't "include node.js", what you need to do is include the script that connects to the server via socket.io (8080 server).
This post may be useful for you http server and web sockets from separate servers.
On the other hand, you can include client side javascript from the 8080 server in order to make the chat run correctly.
Edited for more details.
In the server running on 8080 you can create a server with Socket.io and Express, there you can have the server side logic of your chat and serve the JavaScript file with the client side logic. Let's say, the client JavaScript file is located in http://localhost:8080/yourchat.js (of course, in some sort of real world you may have to generate this file in order to emit data to the correct users)
In the server running on 80 you'll have your div element and a script tag with this source: http://localhost:8080/yourchat.js. Using this pattern you sould be able to embed the chat