Reputation: 7136
Such a dumb question, sorry about that. So I've downloaded node.js/sockets.io/express.js. Trying to make a simple multiplayer game, but starting with hello world currently.
I have the following directory structure:
-index.html
-server.js
-package.json
-node_modules/
The server.js has the following code:
var app = require('express');
var http = require('http');
var io = require('socket.io');
/*
var server = http.createServer(function(req,res){
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<h1>Hello world</h1>');
}).listen(80);
*/
var server = http.createServer(app);
server.listen(80);
var socket = io.listen(server);
var usersCount = 0;
socket.on('conection', function(client){
++usersCount;
console.log('client connecting... client# = ' + userCount);
client.emit('onMessageReceived',{msg:"You are client number: " + userCount});
});
My client code is in index.html, and its contents are:
<html>
<head>
<title> Client Code </title>
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> </script>
</head>
<body>
<script>
$(document).ready(function(){
var socket = new io.Socket({'127.0.0.1',{port:80}});
socket.connect();
socket.on('connect', function(obj){
console.log('client connection successful..');
});
socket.on('onMessageReceived', function(data){
console.log("client has received message: " + data.msg);
});
});
</script>
</body>
and my package.json contains:
{
"name": "hello_world",
"version": "0.0.0",
"description": "hello world test program",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": "",
"author": "",
"license": "BSD",
"dependencies":{
"express":"3.0.5",
"http": "",
"socket.io":""
}
}
Now I'm not sure how to proceed to run the app, if I am even finished. Any help on how to proceed next. I am guessing now I need to have server.js run constantly, and have multiple clients open up index.html to connect to the server.js.
Upvotes: 0
Views: 496
Reputation: 5125
It looks to me that your not declaring your server properly. You need to create an instance of the express server which since express 3.x looks like this
var io = require('socket.io')
, express = require('express');
var app = express()
, server = require('http').createServer(app)
, io = io.listen(server);
You can then set your server listening to a port
server.listen(8080);
You can then render pages
app.get('/', function(req, res){
res.render('index');
});
Upvotes: 1
Reputation: 2922
First, You Don't want to really use port 80 in a hello world program it makes it harder and you have to be a root user, use port 8080 instead it is a world easier than port 80.
then to run the program open the your command line and cd in to the directory of server.js and run node server.js
then open localhost:8080 in the browser and on the console you should see the logs.
hope this helps
Upvotes: 1