node.js - socket.io index.html does not respond - node.js

If I start the server and go to localhost:4000, the server gives out the index.html. But the index.html does not load its style.css and does not connect to the server. But if I double click the local index.html document it connects to the server. What is wrong about my response?
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(4000);
function handler (req, res) {
fs.readFile(__dirname + '/public/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {...}
index.html
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet",type="text/css" href="styles.css"/>
<script type="text/javascript" src="node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js">></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<script>
var socket = io.connect('http://localhost:4000');
socket.on('connect', function(){...}

Have you tried referencing socket.io.js like this?
<script src="/socket.io/socket.io.js"></script>

In your handler function, you appear to be responding to all requests by providing index.html back to the user. This is why your CSS stylesheet and Javascript files are not being returned.

Related

Socket.io connection event not fired

I am beginner to socket.io and trying to make simple hello world like program. It looks like my index.html page loads and connects to the server successfully but the server is not firing the "connection" event. I am sharing my code so that you can figure out what am I doing wrong here.
app.js
var app = require('http');
var io = require('socket.io'), fs = require('fs');
app.createServer(function(req,res){
console.log(req.url);
switch(req.url){
case '/':
fs.readFile('./index.html',function(err,data){
if(err){
res.end('Error');
throw err;
}
res.writeHead(200,{"Context-type":"text/html"});
res.write(data);
res.end();
});
break;
case '/socket.io.js':
fs.readFile('./socket.io.js',function(err,data){
if(err){
res.end('Error');
throw err;
}
res.writeHead(200,{"Context-type":"text/javascript"});
res.write(data);
res.end();
});
}
}).listen(8888);
ios = io.listen(app);
console.log("Listening..");
ios.sockets.on('connection',function(socket){
console.log('connection established.'); //this doesn't show up in CLI
});
Index.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Example</title>
<script src="socket.io.js" type="text/javascript"></script>
<script>
var socket = io.connect('http://localhost:8888');
</script>
</head>
<body>
</body>
</html>
Finally I figured it out myself. All I had to do was to
server = require('http').createServer()
and then pass that server to the listener of socket io i.e.
io.listen(server);
What I was doing wrong that I was passing app = require('http'); to the io.listen(app)

I can't connect to server(AWS Amazon EC2) using Socket.io with Phonegap on iOS device

I uploaded a server-side code to AWS Amazon EC2 with node.js and socket.io.
When I connect to that server from browser(both on desktop and ios safari), it works with no problem.
But, when I create a cordova project and modify some of the codes to comply with cordova, get it run on ios device, it doesn't work!
I tried
<access origin="My-server-side-url-comes-here*"/>
but it didn't solve the problem.
Also, i opened up port :9000 on EC2 for TCP connection.
It seems that socket = io.connect(serverUrl); is causing problem..
I've been struggling to get this work for days now...
Can anyone tell me how to get socket.io work with external host, phonegap, and ios?
server side code uploaded to AWS Amazon EC2 (app.js)
var http = require('http');
var socketio = require('socket.io');
var server = http.createServer(function (request, response){
console.log('server created');
}).listen(9000, function(){
console.log('server running!');
});
var io = socketio.listen(server);
io.sockets.on('connection', function(socket){
socket.on('msg', function(data){
console.log(data);
io.sockets.emit('msg_by_server', "server got your msg:"+data);
});
});
client-side code that works with desktop browsers and iPhone safari(which works fine) (index.html)
<html>
<head>
<script src="https://cdn.socket.io/socket.io-1.0.0.js"></script>
<script>
var socket;
var serverUrl = "sampleURL.compute.amazonaws.com:9000";
window.onload = function(){
socket = io.connect(serverUrl);
socket.on('msg_by_server', function(data){
alert(data);
});
}
var sendMessage = function(){
socket.emit('msg', 'msg from client');
}
</script>
</head>
<body>
<button onclick = 'sendMessage();'>Message Send</button>
</body>
</html>
different client-side code used for phonegap(which doesn't work) (index.html)
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="http://cdn.socket.io/socket.io-1.0.3.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
alert('check1');
var socket="";
app.initialize();
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
alert('check2'); // shows up
var serverUrl = "sameURL.compute.amazonaws.com:9000";
socket =io.connect(serverUrl);
alert('check3'); // doesn't show up
socket.on('connect', function(){
socket.on('msg_by_server', function(data){
alert(data);
});
socket.emit('msg', 'msg from client')
});
}
var sendMessage = function(){
alert(socket);
socket.emit('msg', 'msg from client');
};
</script>
</head>
<body onload="onDeviceReady();">
<!--
i put onload="onDeviceReady();" because
document.addEventListener("deviceready", onDeviceReady, false);
doesn't seem to work for some reason..
-->
<button onclick = 'sendMessage();'>amessageSend</button>
</body>
</html>

Can not Run Node.js server file

I am new to Node.js.
I have my NodeServer.js file which has below code.
var express = require("express");
var app = express();
var port = 60000;
var io = require('socket.io').listen(app.listen(port));
console.log("Listening on port " + port);
io.sockets.on('connection', function (socket) {
socket.emit('message', { message: 'welcome to the chat' });
socket.on('send', function (data) {
io.sockets.emit('message', data);
});
});
When I run this from command prompt , by below code
D:\Path to my application>Node NodeServer.js
It shows message like
info - socket.io started
Listening on port 60000
But when I try to connect to this port from browser by http://127.0.0.1:60000, it shows me below error in command prompt
D:\Path to my application\node_modules\expres
s\lib\application.js:119
this._router.handle(req, res, function(err) {
^
TypeError: Cannot call method 'handle' of undefined
What am I Doing wrong?
Above issue is solved:
Below is my EDIT
Below is my client Script
$(document).ready(function () {
var socket = io.connect('http://127.0.0.1:60000');
});
Below is my desing
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="jquery-1.10.1.min.js" type="text/javascript"></script>
<script src="http://127.0.0.1:60000/socket.io/socket.io.js" type="text/javascript"></script>
<script src="NodeClient.js" type="text/javascript"></script>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
When I run my application I get error of "NetworkError: 404 Not Found - http://127.0.0.1:60000/socket.io/socket.io.js"
I have solved my issue by below steps.
I moved my ClientScript to one specific folder(Scripts).(Say my client Script's name is NodeClient.js)
I removed app.get("/", function(req,res){ your logic should go here }); function from Server script.
added below code app.use(express.static(__dirname + '/Scripts'));
Now it is working the way I want.
I don't know whether it is right way or not, but it is working now for me.
change the following line
var io = require('socket.io').listen(app.listen(port));
by
var io = require('socket.io').listen(port);
app.listen(port) returns an object but we have to run the socket.io and express in same port. To do that simply pass the port variable

Problem with first program in socket.io

I am having some problems in executing my first socket.io program. Here is the code
var io=require('socket.io');
var http=require('http');
server =http.createServer(function(req,res) {
res.writeHead(200,{'Content-Type':'text/html'});
res.write('welcome');
res.end();
});
server.listen(7777);
var socket = io.listen(server);
socket.on('connection', function (client) {
console.log('client connected');
client.emit('news', { hello: 'world' });
client.on('another', function (data) {
console.log(data);
});
});
And here is my client side code
<html>
<head>
<script type="text/javascript" src="http://localhost:7777/socket.io/lib/socket.io.js"> </script>
<script type="text/javascript">
var socket = io.connect("http://localhost:7777");
socket.on('news',function(data) {
alert(data);
socket.emit('another',{my:'data'});
});
</script>
</head>
</html>
EDIT: Now, i get an error in my server terminal "info - client protocol unsupported"
what am i doing wrong here? Thanks
You are trying to import a javascript file from the socket io port instead of the web server port.
<script type="text/javascript" src="http://localhost:7777/socket.io/lib/socket.io.js"> </script>
You need to give the correct src parameter. For newer version of socket io, this would be something like socket/socket.io.js.

Simple nodeJS example not working with socket.io

Have been struggling all day trying to make this simple example work using socket.io. I've tried initially on Windows 7 with Cygwin. Have since also tried on OS X, with the same result.
When running the script, it shows this...
2 May 20:57:47 - socket.io ready - accepting connections
But visiting the index.html page doesnt show a client has even connected.
index.html
<html>
<head>
<script type="text/javascript" src="socket.io.js"></script>
<script type="text/javascript">
var socket = new io.Socket('localhost',{'port':8090});
socket.connect();
socket.on('connect', function(){
console.log('connected');
socket.send('hi!');
});
socket.on('message', function(data){
console.log('message recived: ' + data);
});
socket.on('disconnect', function(){
console.log('disconected');
});
</script>
</head>
<body></body>
</html>
server.js
var http = require('http'), io = require('socket.io'),
server = http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<h1>Hello world</h1>');
});
server.listen(8090);
var socket = io.listen(server);
socket.on('connection', function(client){
console.log('client connected');
client.on('message', function(){
console.log('message arrive');
client.send('some message');
});
client.on('disconnect', function(){
console.log('connection closed');
});
});
Any ideas on what I could be doing wrong? No console messages whatsoever are being displayed. Notably, when i use Firebug to look at the index.html page, no scripts are being embedded, which is odd..Not sure what could be causing that.
You're not loading the socket.io library properly in your index.html file. Try this:
<script type="text/javascript" src="http://localhost:8090/socket.io/socket.io.js"></script>
You're not serving up socket.io.js (or the flash file).
I'd recomend using the CDN:
<script src="http://cdn.socket.io/stable/socket.io.js"></script>
or alternatively use express to serve the socket.io.js file.
edit:
err actually looking closer you're also not serving up index.html
again express could work but for the simple example:
var fs = require('fs');
var index = fs.readFileSync('index.html');
//note the readFileSync is done only in the first tic
.
.
.
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(index);
Use this on the client side as the path !
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
yes, and comment the following line:
// server.listen(8090);

Resources