Can not Run Node.js server file - node.js

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

Related

Error creating socket connection using node js express and socket.io in my project folder on linux server

I am trying to create socket connection using node js express and socket.io in my project folder which is on Linux(Ubuntu) server. After installing nodejs, npm, socketio and express I am unable to create socket connection. Tried to run node app.js but no output comes. Installation is done following the tutorial http://www.programwitherik.com/getting-started-with-socket-io-node-js-and-express/. I am including code for app.js and index.html
//app.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
io.on('connection', function(client) {
console.log('Client connected...');
client.on('join', function(data) {
console.log(data);
});
});
app.use(express.static(__dirname + '/node_modules'));
app.get('/', function(req, res,next) {
res.sendFile(__dirname + '/index.html');
});
server.listen(8000);
//index.html
<!doctype html>
<html lang="en">
<head>
<script src="http://example.abcd.net/socket-app/jquery/dist/jquery.js"></script>
<script src="http://example.abcd.net:8000/socket.io/socket.io.js"></script>
</head>
<body>
<h1>Hello World!</h1>
<div id="future"></div>
<form id="form" id="chat_form">
<input id="chat_input" type="text">
<input type="submit" value="Send">
</form>
</body>
</html>
<script>
var socket = io.connect();
socket.on('connect', function(data) {
socket.emit('join', 'Hello World from client');
});
</script>
example.abcd.net is the sample address in which socket-app is the folder which contains app.js and index.html file. Also how to run it on browser as every tutorial runs it using localhost. Similar code works fine when installed on local machine.
Try using io.connect("http://example.abcd.net:8000"); instead of io.connect();

The server has not found anything matching the requested URI node

I have below folder structure in VS2015:
The server.js has below code:
var express = require('express')
var app = express();
var http = require('http').Server(app);
var path = require('path');
var port = process.env.port || 1337;
app.use(express.static(__dirname + 'client'));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname,'client', 'HTML1.html'));
});
http.listen(port, function () {
console.log(`listning on ${port}`);
})
and Html1.Html has below code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head data-ng-app="imageLoaderApp">
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div>
</div>
<script src="/client/scripts/angular.js"></script>
<script type="text/javascript">
var app = angular.module('imageLoaderApp', []);
app.controller('loadController', function ($scope) {
console.log(`i'm here.'`);
});
</script>
</body>
</html>
When I'm hitting below url in browser
http://localhost:1337/
I'm getting below error in console:
This is happening with all the js files. I even tried to move the html and js files in main folder still getting the same error.
What am I doing wrong?
It looks like HTML1.html is in the client folder. If that is the case I think you need to put the path to the js relative to it so: 'src="scripts/angular.js"'

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>

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

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.

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.

Resources