How to include node.js to static html - javascript

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

Related

Problems using socket.io, socket.io.js not found

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.

Connecting 2 servers via Node Websockets

I have 2 Raspberry Pi running on the same Network.
I am using one as a local web server for my house, I then have another one connected to some devices. I want them to both be able to communicate to each other via web sockets but am having some problems.
My server looks like this:
express = require('express'); //web server
app = express();
server = require('http').createServer(app);
io = require('socket.io').listen(server); //web socket server
server.listen(8080); //start the webserver on port 8080
app.use(express.static('public')); //tell the server that ./public/ contains the static webpages
io.sockets.on('connection', function (socket) { //gets called whenever a client connects
socket.on('Testing',function(data){
console.log("Testing connection");
});
});
My problem comes with the client connection I am really not sure what code to use to try and connect.
I have installed Express and Socket.io on my client and used this code:
console.log('1');
// Connect to server
var io = require('socket.io')
var socket = io.connect('http://192.168.1.138:8080', {reconnect: true});
console.log('2');
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
console.log('3');
But this leads to an error on the io.connect is not a function.
I am not really sure how to get the client to work so any advice is appreciated.
I should add that connecting to my webserver directly via the ip and port does load the webpages I have created successfully.
When using socket.io on the server side as a client you need to do var socket = require('socket.io-client')('http://192.168.1.138:8080', ...);. See https://www.npmjs.com/package/socket.io-client

Socket.io connection local from internet

I have to make a system using socket.io there is the server in local (without port forwarded) (socket.io listen on the port 6255) and the client (socket.io.js) on a web server online hosted by hostinger.
I try to communicate between this two server but I have a connection timed out every time.
Connection on the server side : http://pastebin.com/xAFkserq
Connection on the client side : http://pastebin.com/ZMvbR3hC
Is it possible to communicate between two "networks" ? Or it's just a coding problem ?
Thanks for the help :)
Aren't you missing this?
io.on('connection', function(socket){
console.log('connected');
});
Also, have you tried following the examples in Socket.IO documentation?
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Working with sockets might be tricky, check if your network is blocking the exchange of messages somehow.
You shouldn't call connect on the client side with socket.io
On the client side simply do: var socket = io(); to connect back to the server, once the client JS has been served
Edit:
Since you're not using express and intend to just have a socket.io listener, the examples here should provide the information you need

Socket.io initialization resulting in a 404 network error

I am using nodejs and express to create a basic chat app and I'm getting a network 404 error message when trying to initialize the socket.io object.
<script src="/javascripts/socket.io/socket.io.js-client"></script>
<script type="text/javascript">
var socket = io.connect();
</script>
Tha above code results in a 404 error for some polling call
"NetworkError" 404 Not Found - http://localhost:3000/socket.io/?EIO=3&transport=polling&t=1432851505880-89
I need the polling to run using the following url instead: http://localhost:3000/javascripts/socket.io/?EIO=3&transport=polling&t=1432851505880-89
because I am using express, but not sure how to accomplish this.
Server Side Code:
var app = express();
var server = require( "http" ).createServer( app );
var io = require("socket.io").listen(server);
server.listen(8888);
io.sockets.on('connection', function(socket){
socket.on('send message', function(data){
io.sockets.emit('new message', data);
});
});
module.exports = app;
I have been trying to troubleshoot this one for quite a while now with no success. I appreciate any advice. Commenting out the var socket = io.connect() resolves the error. Appreciate any advice.
Thanks
Your web page is apparently running on port 3000, but your socket.io server is listening on port 8888. The two must be the same port so it is no surprise that there is no response for a socket.io request on port 3000 (since your socket.io server is listening on port 8888).
Because the default URL it is trying is port 3000, then that must be the port that your web page is one and it must be served by a different web server. If that is the case, then you will need to do one of two things:
Combine the web server that serves your web pages with the socket.io server so the same server is taking care of both.
Specify the port in the client request and enable your socket.io server for cross-origin requests.
To specify the port in the client request, you can do this:
<script src="http://myserver.com:8888/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io("http://yourserver.com:8888");
</script>
Note, that this is requesting the client socket.io library from the express server where your socket.io server is (so it's using the same port that your socket.io server is running on).
If the HTML where socket.io client javascript is being served is not also being served by express at port 8888 (it looks like the html is coming from port 3000), you may just need to configure the socket.io client to point at the port where the server-side socket.io has been setup to listen (8888):
var socket = io.connect('localhost:8888');

Cross domain connections in Node.js

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))

Categories