I made an online multiplayer game. I works perfectly when I run it with node.js command prompt on localhost:3000. But when I try to run it on the website it is not doing what my app.js file says it to do. my questions are;
How can I make my node.js project run on my website rather than on localhost?
What will the port be instead of 3000?
Can I do this by uploading some file into my website via ftp?
Here is my app.js file
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
var usernumm = 0;
var usernum1 = [];
app.use(express.static(__dirname + '/public'));
server.listen(3000);
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket){
var endpoint = socket.manager.handshaken[socket.id].address;
console.log('***New connection from ' + endpoint.address + ':' + endpoint.port);
usernumm++;
io.sockets.emit('usernum', usernumm);
usernum1[usernumm] = endpoint.port;
console.log('usernum'+usernumm+'geldi'+findusernum());
socket.on('button1socket', function(){
io.sockets.emit('button1f', findusernum() );
console.log('user '+findusernum()+' pressed a button');
});
socket.on('buttonclickable', function(){
io.sockets.emit('buttonclickable1', findusernum() );
});
socket.on('disconnect', function () {
usernumm--;
io.sockets.emit('usernum', usernumm);
//sockets[usernum] = socket.port;
console.log('***Client disconnected');
});
//finds number of online users
function findusernum(){
for(var i = 0; i<9;i++){
if(usernum1[i] == endpoint.port){return i;}else{}
}
}
});
try:
var express = require('express');
var app = express();
var httpServer = require('http').Server(app);
var socketServer = require('socket.io')(httpServer);
var ip = 'iphere';
var port = 80;
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
socketServer.on('connection', function(socket){
console.log("A Client has connected.");
socket.on('disconnect', function(){
console.log("A Client has disconnected.");
});
});
httpServer.listen(port, ip, function(){
console.log("Listening to "+ip+":"+port);
});
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script type="text/javascript" src="http://ip:port/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket;
try{
socket = io("http://ip:port/", {'forceNew':true });
socket.on('connect', function(error){
if(error){
}
});
}catch(e){
}
</script>
</head>
<body>
</body>
</html>
after you have specified your ip and port
port forward the port you have specified to live your website/game using your router
then you can visit it with http://yourpublicip:port/
if its port 80 then visit the page without the port.
Related
So, my program gets data from udp server and i just want to display it in list in HTML page 1 by 1 when it updates.
In console it works, but how to do it on page?
I got this code
index.js
var dgram = require('dgram'),
server = dgram.createSocket('udp4'); //this server gets data from udp packet
var msg;
server.on('message', function (message, rinfo) {
msg = message.toString('ascii'); //udp packet data to string
console.log(msg);
});
server.on('listening', function () {
var address = server.address();
console.log('UDP Server listening ' + address.address + ':' + address.port);
});
server.bind(8007);
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket) {
var tm = setInterval(function() {
socket.emit('datafromserver', {'datafromserver': msg});
}, 500);
socket.on('disconnect', function() {
clearInterval(tm);
});
});
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
and html page
<!doctype html>
<html>
<head>
<title>Scoreboard</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
</style>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io.connect('http://192.168.1.162:3000/');
socket.on('#dataonscreen', function(data) {
$('#dataonscreen').html(data.datafromserver);
console.log(data.datafromserver);
});
</script>
<ul id="dataonscreen"></ul>
</body>
</html>
I can't understand why this isn't working and how to fix it.
Please help!
Your socket.io server emits datafromserver while your code listens for #dataonscreen
Change either so that they are the same value and your code should work. I'm not sure how you have console output since the event is not being listened for
I am trying to send data bidirectionally between a node server and browser client.
I can get information from the Node server to the browser client but not vice versa. I dont understand what I am doing wrong, please help.
Node server.js
var express = require('express')
var app = express();
var http = require('http').Server(app);
var socketTx = require('socket.io')(http);
app.use(express.static(__dirname + '/'))
http.listen(3000, function(){
console.log('listening on http://127.0.0.1:3000');
});
// 1) Send initial data from node to browser
setInterval( function() {
var msg = Math.random();
socketTx.emit('Node', msg);
}, 1000);
var io = require('socket.io-client');
var socketRx = io.connect('http://localhost:3000', {reconnect: true});
// 4) Receive data from browser and log in node console
socketRx.on('Browser', function(msg){
console.log(msg);
});
Browser index.html
<html>
<head></head>
<body>
<div id="message"></div>
<script src="/socket.io/socket.io.js"></script>
<script src="socket.js"></script>
</body>
</html>
Browser socket.js
var socketRx = io();
var socketTx = io();
// 2) Receive initial data from node and display in browser
socketRx.on('Node', function(msg){
document.getElementById("message").innerHTML = msg;
// 3) Send data from browser back to node
socketTx.emit('Browser', msg);
});
I'm not familiar with socket.io, sorry if there are mistakes.
By refering to this official document, I fixed server.js as below.
It has been working fine in my environment. Please try this code.
var express = require('express')
var app = express();
var http = require('http').Server(app);
var socketTx = require('socket.io')(http);
app.use(express.static(__dirname + '/'))
http.listen(3000, function(){
console.log('listening on http://127.0.0.1:3000');
});
// 1) Send initial data from node to browser
setInterval( function() {
var msg = Math.random();
socketTx.emit('Node', msg);
}, 1000);
var io = require('socket.io-client');
io.connect('http://localhost:3000', {reconnect: true});
// 4) Receive data from browser and log in node console
socketTx.on('connection', function(socket) {
socket.on('Browser', function(msg){
console.log(msg);
});
});
I have been working on node.js project. my requirement is I want to load.txt file on browser. when I change and save this file, content should be updated. Browser should be auto refresh.
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
index.js
app.get('/', function(req, res){
res.sendFile(__dirname + '/demo.txt');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
var io = require('socket.io')(80);
var fs = require('fs');
fs.watchFile('message.text', (curr, prev) => {
console.log(`the current mtime is: ${curr.mtime}`);
console.log(`the previous mtime was: ${prev.mtime}`);
// file changed push this info to client.
io.emit('fileChanged', 'yea file has been changed.');
});
index.html
<script>
var socket = io();
socket.on('fileChanged', function(msg){
alert(msg);
});
First of all you can do this with two action:
1. Watch file change on server-side. And push info to client
You can watch file with node.js.
var app = require('express')();
var http = require('http').Server(app);
app.get('/', function(req, res){
res.sendFile(__dirname + '/cluster.json');
});
const io = require('socket.io')(http);
io.on('connection',function (client) {
console.log("Socket connection is ON!");
});
http.listen(80, function(){
console.log('listening on *:80');
});
var fs = require('fs');
fs.watchFile('cluster.json', function(curr, prev){
// file changed push this info to client.
console.log("file Changed");
io.emit('fileChanged', 'yea file has been changed.');
});
2. Catch "file changed" info and refresh page on client side
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script type="text/javascript" src="node_modules/socket.io-client/dist/socket.io.js"></script>
<script>
var socket = io("http://localhost:80");
socket.on('fileChanged', function(msg){
alert(msg);
});
</script>
</body>
</html>
The best way to do this is using WebSockets. A very good package to work with WebSockets is Socket.io, and you can use something like chokidar or the native function fs.watch to watch the file changes and then emit an messsage.
Or if you trying to do this only for development purposes, you should check webpack, gulp or other task runner that have built-in functions to do this.
Do polling for the file using Ajax. Your server could respond with {changes: '{timestamp-of-file-modify}'}. Now check if your last seen change time differs from response time.
If there is changes: window.location.reload
js application. Need help to resolve this issue.
I have app.js which is node, calls index.html. The index.html intern calls main.js function clicked. It works fine when I have funtion 'clicked()' embeded inside index.html using script tag. But does not work if function clicked is in a seperate js file. I think this is something regarding to node.js but unable to figure out. Please find my code below.
app.js
var http = require('http');
var fs = require('fs');
var express = require('express');
var path = require('path');
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
var request = require('request');
request('http://localhost:8000/test', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
});
var server = http.createServer(function(req,res){
console.log('Request was made:' + req.url);
res.writeHead(200,{'content-Type': 'text/html'});
var myReadStream = fs.createReadStream(__dirname + '/index.html','utf8');
myReadStream.pipe(res);
});
server.listen(3000,'127.0.0.1');
console.log('Listening on port 3000');
index.html
<!DOCTYPE html>
<html>
<head>
<title> Login</title>
<script type="text/javascript" src="main.js"></script>
<center>
<h1> Login </h1>
</center>
</head>
<body>
<center>
<input type="text" id="username" placeholder="UserName"></br>
<input type="password" id="password" placeholder="PassWord"></br>
<input type="button" value="Login" onclick="clicked()">
</center>
</body>
</html>
main.js
function clicked() {
var user = document.getElementById('username');
var pass = document.getElementById('password');
var checkuser = "test";
var checkpass = "123"
if (user.value == checkuser) {
if (pass.value == checkpass) {
window.alert("You are logged in as "+ "'"+user.value+"'");
open("http://www.yahoo.com");
}
else
window.alert("Incorrect username or Password");
}
else
window.alert("Incorrect username or Password");
}
ScreenShot of the Error:
This is because the Node.js server does not serve main.js correctly -- According to the browser's "Resources" panel, main.js is available, but its path is not /main.js.
Low level Node.js server code and Express framework code co-exist, which is not a good idea.
To solve the problem with low level Node.js code:
var server = http.createServer(function(req,res){
console.log('Request was made:' + req.url);
if (req.url === '/main.js') {
res.writeHead(200,{'content-Type': 'application/javascript'});
var jsReadStream = fs.createReadStream(__dirname + '/main.js','utf8');
jsReadStream.pipe(res);
return;
}
res.writeHead(200,{'content-Type': 'text/html'});
var myReadStream = fs.createReadStream(__dirname + '/index.html','utf8');
myReadStream.pipe(res);
});
To solve the problem with Express framework:
var http = require('http');
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.get('/main.js', function(req, res) {
res.sendFile(path.join(__dirname + '/main.js')); // where main.js located.
});
app.set('port', 3000);
var server = http.createServer(app);
server.listen(port);
You are using both http and express, which is probably unnecessary. I would serve static files with app.use(express.static('public')), per the docs. Then you can serve the index with
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/index.html'))
});
And start the server with app.listen(3000);
I recently started using Socket.io, and node.js as a result, and I am kind of stuck. I do not even know if this is a practical solution for my application, but hopefully someone can help.
All I have here is a webpage with a checkbox, which reports it's status to the node console, and then when a TCP client connects, it receives the status as well.
I am wondering how I would go about making this event continuous, so that the TCP client constantly receives updates on the status of the checkbox.
If anyone has any idea, please let me know, and sorry for the long code...
Server Code:
var net = require('net');
var app = require('express')(); <!-- These are mandatory variables -->
var http = require('http').Server(app);
var io = require('socket.io')(http);
var HOST = 'localhost';
var PORT = 4040;
GLOBAL.MYVAR = "Hello world";
var server = net.createServer();
server.listen(PORT, HOST);
app.get('/', function(req, res){ <!-- This sends the html file -->
//send the index.html file for all requests
res.sendFile(__dirname + '/index.html');
});
http.listen(3001, function(){ <!-- Tells the HTTP server which port to use -->
console.log('listening for HTTP on *:3001'); <!-- Outputs text to the console -->
console.log('listening for TCP on port ' + PORT);
});
<!-- everything below this line are actual commands for the actual app -->
io.on('connection', function(socket) // Opens the socket
{
socket.on('checkbox1', function(msg){ // Creates an event
console.log(msg); // displays the message in the console
MYVAR = msg; // Sets the global variable to be the contents of the message recieved
});
});
server.on('connection', function(socket){ // Opens the socket for the TCP connection
socket.write(MYVAR);
}).listen(PORT, HOST);
Client code:
<!doctype html>
<html>
<head>
<title>Socket IO Test</title>
<form action="">
<input type='checkbox' onclick='checkbox1(this);'>Checkbox1</label>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
var number = 0;
function checkbox1(cb) {
socket.emit('checkbox1', 'checkbox 1 = ' + cb.checked);
return false;
}
</script>
</body>
</html>
Cheers
I believe the issue here is that you don't have a way to reference the TCP socket. Once you do have a reference it is as easy as receiving a message and sending it.
This will work for a single client.
var net = require('net');
var app = require('express')(); <!-- These are mandatory variables -->
var http = require('http').Server(app);
var io = require('socket.io')(3000);
var s;
var HOST = 'localhost';
var PORT = 4040;
GLOBAL.MYVAR = "Hello world";
var server = net.createServer();
server.listen(PORT, HOST);
app.get('/', function(req, res){ <!-- This sends the html file -->
//send the index.html file for all requests
res.sendFile(__dirname + '/index.html');
});
http.listen(3001, function(){ <!-- Tells the HTTP server which port to use -->
console.log('listening for HTTP on *:3001'); <!-- Outputs text to the console -->
console.log('listening for TCP on port ' + PORT);
});
<!-- everything below this line are actual commands for the actual app -->
io.on('connection', function(socket) // Opens the socket
{
socket.on('checkbox1', function(msg){ // Creates an event
console.log(msg); // displays the message in the console
MYVAR = msg; // Sets the global variable to be the contents of the message recieved
s.write(MYVAR, 'utf-8');
});
});
server.on('connection', function(socket){ // Opens the socket for the TCP connection
s = socket;
s.write(MYVAR, 'utf-8');
}).listen(PORT, HOST);
This will work for multiple clients.
var net = require('net');
var app = require('express')(); <!-- These are mandatory variables -->
var http = require('http').Server(app);
var io = require('socket.io')(3000);
var sockets = [];
var HOST = 'localhost';
var PORT = 4040;
GLOBAL.MYVAR = "Hello world";
var server = net.createServer();
server.listen(PORT, HOST);
app.get('/', function(req, res){ <!-- This sends the html file -->
//send the index.html file for all requests
res.sendFile(__dirname + '/index.html');
});
http.listen(3001, function(){ <!-- Tells the HTTP server which port to use -->
console.log('listening for HTTP on *:3001'); <!-- Outputs text to the console -->
console.log('listening for TCP on port ' + PORT);
});
<!-- everything below this line are actual commands for the actual app -->
io.on('connection', function(socket) // Opens the socket
{
socket.on('checkbox1', function(msg){ // Creates an event
console.log(msg); // displays the message in the console
MYVAR = msg; // Sets the global variable to be the contents of the message recieved
for (var i = 0; i < sockets.length; i++) {
if(sockets[i]) {
sockets[i].write(MYVAR, 'utf-8');
}
}
});
});
server.on('connection', function(socket){ // Opens the socket for the TCP connection
sockets.push(socket);
socket.write(MYVAR, 'utf-8');
}).listen(PORT, HOST);