I have some node.js code that I am running called app.js When it runs is gives an error saying connection refused?
It is running on plesk so I cannot debug it. I have added the package.json too but maybe I am missing something?
package.json:
{
"name": "socket-example",
"version": "0.0.1",
"description": "test socket.io app",
"dependencies": {
"socket.io": "^1.7.3"
},
"scripts": {
"start": "node app.js"
}
}
app.js:
var http = require('http');
var fs = require('fs');
// Loading the index file . html displayed to the client
var server = http.createServer(function(req, res) {
fs.readFile('./index.html', 'utf-8', function(error, content) {
res.writeHead(200, {"Content-Type": "text/html"});
res.end(content);
});
});
// Loading socket.io
var io = require('socket.io').listen(server);
// When a client connects, we note it in the console
io.sockets.on('connection', function (socket) {
console.log('A client is connected!');
});
server.listen(8080);
index.html:
<body>
<h1>Communicating with socket.io!</h1>
<p><input type="button" value="Poke the server" id="poke" /></p>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
// The visitor is asked for their username...
var username = prompt('What\'s your username?');
// It's sent with the signal "little_newbie" (to differentiate it from "message")
socket.emit('little_newbie', username);
// A dialog box is displayed when the server sends us a "message"
socket.on('message', function(message) {
alert('The server has a message for you: ' + message);
})
// When the button is clicked, a "message" is sent to the server
$('#poke').click(function () {
socket.emit('message', 'Hi server, how are you?');
})
</script>
</body>
Try changing all you code like this as this will resolve your issues
app.js
var express = require('express');
var app = express();
app.set("view engine","html");
var http = require('http');
//making express server for routes
var server = http.Server(app);
// Loading socket.io
var io = require('socket.io')(server);
//index route
//loaded when the website is loaded root route.
app.get('/',function(req,res){
//specify the path to the directory (assuming both are in the same directory)
res.sendFile(__dirname + '/index.html');
})
// When a client connects, we note it in the console
io.sockets.on('connection', function (socket) {
console.log('A client is connected!');
//message of client side
socket.on('little_newbie',function(message){
//give the username in terminal of the connected client
console.log(message);
//send a hello to the client from the server.
io.sockets.emit('message',"Hello "+message);
})
//button poke mesage response
socket.on('message',function(message){
//print the hello message from the server
console.log(message)
//after this you can send a response back to the client as in the above case
io.sockets.emit('poke',"Hi I am fine ");
})
});
server.listen(8080);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Socket.io</title>
</head>
<body>
<h1>Communicating with socket.io!</h1>
<p><input type="button" value="Poke the server" id="poke" /></p>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('/');
// The visitor is asked for their username...
var username = prompt('What\'s your username?');
// It's sent with the signal "little_newbie" (to differentiate it from "message")
socket.emit('little_newbie', username);
// A dialog box is displayed when the server sends us a "message"
socket.on('message', function(message) {
alert('The server has a message for you: ' + message);
})
// When the button is clicked, a "message" is sent to the server
$('#poke').click(function () {
socket.emit('message', 'Hi server, how are you?');
})
socket.on('poke',function(message){
alert(message);
})
</script>
</body>
{
"name": "socket-example",
"version": "0.0.1",
"description": "test socket.io app",
"dependencies": {
"express": "^4.16.4",
"socket.io": "^1.7.3"
},
"scripts": {
"start": "node app.js"
}
}
There ate no routes configuration , and when you try to ping from browser it won't connect . just like meaning less URI. Try making a route and then calking route from Browser.
Related
I am learning to use node.js on a public server as a open line from server to clients (https://github.com/iamshaunjp/websockets-playlist/tree/lesson-5).
I have done a youtube tutorial to create a chat server / client. This works on my own machine.
The server code (index.js):
var express = require('express');
var socket = require('socket.io');
// App setup
var app = express();
var server = app.listen(4000, function () {
console.log('listening to request on port 4000');
})
// Static files
app.use(express.static('public'));
// Socket setup
var io = socket(server);
io.on('connection', function (socket) {
console.log('made socket connection', socket.id);
socket.on('chat', function (data) {
io.sockets.emit('chat', data);
});
socket.on('typing', function (data) {
socket.broadcast.emit('typing', data);
});
});
The browser code (/public/chat.js):
// Make connection
var socket = io.connect('http://localhost:4000');
// Query DOM
var message = document.getElementById('message');
var handle = document.getElementById('handle');
var btn = document.getElementById('send');
var output = document.getElementById('output');
var feedback = document.getElementById('feedback');
// Emit events
btn.addEventListener('click', function () {
socket.emit('chat', {
message: message.value,
handle: handle.value
});
});
message.addEventListener('keypress', function () {
socket.emit('typing', handle.value);
});
// Listen for events
socket.on('chat', function (data) {
feedback.innerHTML = '';
output.innerHTML += '<p><strong>' + data.handle + ':</strong>' + data.message + '</p>';
});
socket.on('typing', function (data) {
feedback.innerHTML = '<p><em>' + data + ' is typing a message...</em></p>';
});
The browser code (public/index.html):
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Websockets 101</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
<link href="/styles.css" rel="stylesheet" />
</head>
<body>
<div id="mario-chat">
<div id="chat-window">
<div id="output"></div>
<div id="feedback"></div>
</div>
<input id="handle" type="text" placeholder="Name" />
<input id="message" type="text" placeholder="Message" />
<button id="send">Send</button>
</div>
<script src="/chat.js"></script>
</body>
</html>
When i go to http://localhost:4000 i see the chat screen and i can chat (to multiple browser windows).
now i want to upload my code to the ubuntu development server but i can't get it working. I have installed Node.js on the server and when i type node -v i get the version number so the installation is correct.
What is my next step? If i upload the code to the development server (http://devserver01/websocket/) it won't display my code because i don't have an index.html.
On the localhost i have used this code (package.json):
{
"name": "websocket",
"version": "1.0.0",
"description": "websocket",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"socket.io": "^2.3.0"
},
}
If i go to http://devserver01/websocket/ it doesnt work (ofcourse), but also http://devserver01:4000 doesn't work (also ofcourse because it can't know it has to go to the js file).
But i cannot find any information on how to deploy this on a remote linux machine.
Thank you for the help!
I found a coding from tutorials point to run a a simple socket.io chat server in localhost, I installed necessary environments like nodejs, express, init package.json and I started the server from terminal using command-"node app.js", then I accessed the index page in my localhost it showed the chat page, it is working fine. But the thing is I want to use this is in a live server for my office, to chat within the office. Is this code is enough for that. I am new to this socket.io and nodejs. My office has live server for hosting their website, this code opens and listens to port 3000. It will be highly helpful if you could tell me how to run this in a real server.
Index.html
<!DOCTYPE html>
<html>
<head>
<title>Hello world</title>
</head>
<script src = "/socket.io/socket.io.js"></script>
<script>
var socket = io();
function setUsername() {
socket.emit('setUsername', document.getElementById('name').value);
};
var user;
socket.on('userExists', function(data) {
document.getElementById('error-container').innerHTML = data;
});
socket.on('userSet', function(data) {
user = data.username;
document.body.innerHTML = '<input type = "text" id = "message">\
<button type = "button" name = "button" onclick = "sendMessage()">Send</button>\
<div id = "message-container"></div>';
});
function sendMessage() {
var msg = document.getElementById('message').value;
if(msg) {
socket.emit('msg', {message: msg, user: user});
}
}
socket.on('newmsg', function(data) {
if(user) {
document.getElementById('message-container').innerHTML += '<div><b>' +
data.user + '</b>: ' + data.message + '</div>'
}
})
</script>
<body>
<div id = "error-container"></div>
<input id = "name" type = "text" name = "name" value = ""
placeholder = "Enter your name!">
<button type = "button" name = "button" onclick = "setUsername()">
Let me chat!
</button>
</body>
</html>
app.js Server
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');
});
users = [];
io.on('connection', function(socket) {
console.log('A user connected');
socket.on('setUsername', function(data) {
console.log(data);
if(users.indexOf(data) > -1) {
socket.emit('userExists', data + ' username is taken! Try some
} else {
users.push(data);
socket.emit('userSet', {username: data});
}
});
socket.on('msg', function(data) {
//Send message to everyone
io.sockets.emit('newmsg', data);
})
});
http.listen(3000, function() {
console.log('listening on localhost:3000');
});
You can solve your problem through nginix( A reverse proxy server). Nginx have .conf file which contains the server realted configuration.
server { listen 3000; server_name io.yourhost.com; }
To run:
Sudo service nginx start
It will start your server on given IP or Domain name.
Change the declaration variable socket by
var socket = io(Server IP + ':port');
Example:
var socket = io('127.0.0.1:3000);
I using socket.io version 2.0.2
Im busy with a chat app with nodejs 6 socketio 1.7.2 express 4.14.1.
i can run node index.js but as soon as i access my page simplechat.html
it throws the below error. Please help
/root/Chat/node_modules/express/lib/response.js:1013
setImmediate(function () {
^ ReferenceError: setImmediate is not defined
at Array.onfinish [as 0] (/root/Chat/node_modules/express/lib/response.js:1013:5)
at listener (/root/Chat/node_modules/express/node_modules/on-finished/index.js:169:15)
at onFinish (/root/Chat/node_modules/express/node_modules/on-finished/index.js:100:5)
at callback (/root/Chat/node_modules/express/node_modules/on-finished/node_modules/ee-first/index.js:55:10)
at ServerResponse.onevent (/root/Chat/node_modules/express/node_modules/on-finished/node_modules/ee-first/index.js:93:5)
at ServerResponse.EventEmitter.emit (events.js:126:20)
at ServerResponse.OutgoingMessage._finish (http.js:837:8)
at ServerResponse.OutgoingMessage.end (http.js:822:10)
at onend (stream.js:66:10)
at EventEmitter.emit (events.js:126:20)
Package json file
{
"name": "Chat",
"version": "0.0.0",
"description": "ERROR: No README.md file found!",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": "",
"author": "",
"license": "BSD",
"dependencies": {
"express": "~4.14.1",
"socket.io": "~1.7.2"
}
Index.js File
// We need to use the express framework: have a real web server that knows how to send mime types etc.
var express=require('express');
// Init globals variables for each module required
var app = express()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server);
// Indicate where static files are located
//app.configure(function () {
app.use(express.static(__dirname + '/'));
//});
// launch the http server on given port
server.listen(8000,'***.***.**.**');
console.log('Server running at http://***.***.***.**:8000/');
// routing
app.get('/', function (req, res) {
res.sendFile(__dirname + '/simpleChat.html');
});
// usernames which are currently connected to the chat
var usernames = {};
io.sockets.on('connection', function (socket) {
// when the client emits 'sendchat', this listens and executes
socket.on('sendchat', function (data) {
// we tell the client to execute 'updatechat' with 2 parameters
io.sockets.emit('updatechat', socket.username, data);
});
// when the client emits 'adduser', this listens and executes
socket.on('adduser', function(username){
// we store the username in the socket session for this client
socket.username = username;
// add the client's username to the global list
usernames[username] = username;
// echo to client they've connected
socket.emit('updatechat', 'SERVER', 'you have connected');
// echo globally (all clients) that a person has connected
socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected');
// update the list of users in chat, client-side
io.sockets.emit('updateusers', usernames);
});
// when the user disconnects.. perform this
socket.on('disconnect', function(){
// remove the username from global usernames list
delete usernames[socket.username];
// update list of users in chat, client-side
io.sockets.emit('updateusers', usernames);
// echo globally that this client has left
socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
});
});
SimpleChat.html
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
var socket = io.connect(); // we might pass the URL of the WS server as parameter here
// on connection to server, ask for user's name with an anonymous callback
socket.on('connect', function(){
// call the server-side function 'adduser' and send one parameter (value of prompt)
socket.emit('adduser', prompt("What's your name?"));
});
// listener, whenever the server emits 'updatechat', this updates the chat body
socket.on('updatechat', function (username, data) {
$('#conversation').append('<b>'+username + ':</b> ' + data);
});
// listener, whenever the server emits 'updateusers', this updates the username list
socket.on('updateusers', function(data) {
$('#users').empty();
$.each(data, function(key, value) {
$('#users').append('<div>' + key + '</div>');
});
});
// on load of page
$(function(){
// when the client clicks SEND
$('#datasend').click( function() {
var message = $('#data').val();
$('#data').val('');
// tell server to execute 'sendchat' and send along one parameter
socket.emit('sendchat', message);
});
// when the client hits ENTER on their keyboard
$('#data').keypress(function(e) {
if(e.which == 13) {
$(this).blur();
$('#datasend').focus().click();
}
});
});
</script>
<div style="float:left;width:100px;border-right:1px solid black;height:300px;padding:10px;overflow:scroll-y;">
<b>USERS</b>
<div id="users"></div>
</div>
<div style="float:left;width:300px;height:250px;overflow:scroll-y;padding:10px;">
<div id="conversation"></div>
<input id="data" style="width:200px;">
<input type="button" id="datasend" value="send">
</div>
Does anyone has experience to have Node.js and socket.io working on Cloud9 IDE?
The "Example (NodeJS with Socket.io)" (at https://c9.io/site/blog/2013/05/native-websockets-support/) doesn't work.
First, the server (https://c9.io/etlolap/webapp, /test.js) throws an error unless I fix as follow. I clicked Run button while test.js is on active tab.
var
socketIo = require('socket.io'),
io = socketIo.listen(Number(process.env.PORT));
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Then, my client (https://c9.io/etlolap/webapp, /test.html) still cannot connect. I clicked Preview button while test.html is on active tab.
<!doctype html>
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('https://webapp-c9-etlolap.c9.io');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
</head>
<body>
Loading...
</body>
</html>
and got error message below.
Failed to load resource: the server responded with a status of 404 --- (Not Found) https://c9.io/socket.io/socket.io.js
Uncaught ReferenceError: io is not defined --- test.html:6
1. Steps
1.1) Run server.js
The cloud 9 console shows up:
1.2) Hit Preview on index.html
1.3) Then a window is opening on the right side of your IDE. You can either hit the button in the middle of the navigation bar or copy and paste the url into a new browser window.
1.4) Socket communication is working!
2. Prerequisite
2.1) node module socket.io
Hit F6 or View -> Console and install socket.io.
2.2) the client side JavaScript from socket.io
Since I didn't find an official link to download it, I created a GitHubGist.
socket.io.js
3. Code
server.js
// module dependencies
var http = require("http"),
sio = require("socket.io");
// create http server
var server = http.createServer().listen(process.env.PORT, process.env.IP),
// create socket server
io = sio.listen(server);
// set socket.io debugging
io.set('log level', 1);
io.sockets.on('connection', function (socket) {
socket.emit('news', { message: 'Hello world!' });
socket.on('my other event', function (data) {
console.log(data.message);
});
});
index.html
<!DOCTYPE html>
<html>
<script src="js/socket.io.js"></script>
<script>
var socket = io.connect("https://demo-project-c9-matthiasholdorf.c9.io");
socket.on("news", function(data) {
console.log(data.message);
});
socket.emit("my other event", { message : "client emit" } );
</script>
</html>
Thanks for feedback from damphat and Matthias. After many failed attempts, finally I figured out the solution myself.
On Cloud9 IDE, the typical line in client (test.html here) has to be changed from,
<script src="/socket.io/socket.io.js"></script>
to
<script src="https://webapp-c9-etlolap.c9.io/socket.io/socket.io.js"></script>
The prefix is the URL of your Cloud9 project URL. By changing this line, my example worked.
you must flowing these step:
open the terminal on https://c9.io/etlolap/webapp, type:
npm install socket.io
node test
then open a new tab of browser with url
https://webapp-c9-etlolap.c9.io/socket.io/socket.io.js
You will see socket.io.js source code
I did not how you open test.html in c9.io without http server, did you just press preview?
Edit:
To return html files, you should merge http server and socket.io server like this:
// file: test.js
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen( Number( process.env.PORT ) );
function handler (req, res) {
fs.readFile(__dirname + '/test.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) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
To fetch any html file requested, using html files located in the file folder, you can use express:
var fs = require('fs');
var express = require('express');
var app = express();
// This fetches html files from the client folder (if they exist), and returns a "Page could not be found" error otherwise (this can be customized to some other 404 error page as desired)
app.get('*', function (req, res) {
var urlReading = req.url;
if (urlReading == "/")
{
urlReading = "/index.html";
}
urlReading = __dirname + "/client" + urlReading;
console.log("Loading: " + urlReading);
fs.readFile(urlReading, function (err, html) {
if (err) {
console.log("Could not find " + urlReading)
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end("<html><head><title>Page could not be found</title></head><body><h1>Page could not be found</h1></body></html>");
}
else
{
console.log("Found " + urlReading)
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(html);
}
});
});
app.listen(process.env.PORT, process.env.IP);
I know this question is kind of awkward, but the problem comes from Samsung TV 2010 / 2011 SmartTV (and blue ray player; of course 2012 emulator working fine). I ported the simple chatting examples come from the source and package to SmartTV app. Both of them fall back to JSONP polling, but from SmartTV app only could emit / push to server once. Receiving the message from server could be multiple times without any problem. After looking for the answer in Samsung D forum (of course nothing there), I think the fastest way to work around this issue is to deploy an Express server, taking the post data and JSON.parse, then emit Socket.io / Sockjs internally inside the server itself.
Could anybody show me an easy sample code so I could start from there? Thanks a lot.
I quickly make code, but seems it doesn't work:
lib/server.js
var express = require('express')
, app = express.createServer()
, io = require('socket.io').listen(app);
app.listen(80);
app.use(express.bodyParser());
app.get('/', function (req, res) {
res.sendfile('/var/www/mpgs_lite_v3/index.html');
});
app.post('/', function(req, res){
console.log(req.body);
io.sockets.emit('my other event', req.body);
res.redirect('back');
});
io.sockets.on('connection', function (socket) {
//socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
index.html
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
</head>
<body>
<form method="post" action="/">
<input type="hidden" name="_method" value="put" />
<input type="text" name="user[name]" />
<input type="text" name="user[email]" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
'my other event' seems not receive anything.
UPDATE: I updated the example for you to make it more complete. I didn't have an app.listen before, and here is also a client side script which shows that it, indeed, works fine:
<!doctype html>
<html>
<head>
<script src="//www.google.com/jsapi"></script>
<script src="/socket.io/socket.io.js"></script>
<script>google.load("jquery", "1.7.1")</script>
<script>
var socket = io.connect("localhost", {port: 3000});
socket.on("foo", function(message) { console.log("foo: ", message) });
$(function() {
$("button").click(function() {
$.post("/foo", { message: $("input").val() });
});
});
</script>
</head>
<body>
<input type=text>A message</input>
<button>Click me!</button>
</body>
</html>
And the server, now with an app.listen directive:
var express = require("express"),
app = express.createServer(),
io = require("socket.io").listen(app)
index = require("fs").readFileSync(__dirname + "/index.html", "utf8");
app.use(express.bodyParser());
app.get("/", function(req, res, next) {
res.send(index);
});
app.post("/foo", function(req, res, next) {
io.sockets.emit("foo", req.body);
res.send({});
});
app.listen(3000);
Usage:
node app.js
Navigate to http://localhost:3000/ and click the button. Check your console for output.
Based on SockJS express example server.js could look like:
var express = require('express');
var sockjs = require('sockjs');
// 1. Echo sockjs server
var sockjs_opts = {sockjs_url: "http://cdn.sockjs.org/sockjs-0.2.min.js"};
var sockjs_echo = sockjs.createServer(sockjs_opts);
connections = {};
sockjs_echo.on('connection', function(conn) {
console.log(conn.id);
connections[conn.id] = conn
conn.on('close', function() {
delete connections[conn.id];
});
// Echo.
conn.on('data', function(message) {
conn.write(message);
});
});
// 2. Express server
var app = express.createServer();
sockjs_echo.installHandlers(app, {prefix:'/echo'});
console.log(' [*] Listening on 0.0.0.0:9999' );
app.listen(9999, '0.0.0.0');
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
app.post("/send", function(req, res, next) {
for(var id in connections) {
connections[id].write('received POST');
}
res.send({});
});
To test open browser at localhost:9999 and run:
curl localhost:9999/send -X POST
just remove this comment
//socket.emit('news', { hello: 'world' });
to
socket.emit('news', { hello: 'world' });
it will work because its emiting data through news and you are listening using my other event instead of 'news' or you can do just listen using 'my other event'
I don't know if this would help, but you can make an emit abstraction on the client based on your browser and then make a separate get function on the server that will handle the request the same way as the socket.on callback. In order to know where to send the information I suggest you use some key that you can store in a hash table in the server and local storage on the client.
For the client:
var emit = function(event, options) {
if ("WebSocket" in window) {
socket.emit(event, options);
console.log("emited via WebSocket");
} else {
$.post("http://localhost/emit/" + event, options);
console.log("emited via AJAX");
}
}
emit("echo", {
key: localStorage.getItem("key"),
data: {
hello: "world"
}
});
socket.on("response", function(data) {
console.log(data.hello); //will print "world"
});
For the server:
var sockets = {};
var echo_handler = function(a) {
var socket = sockets[a.key];
var data = a.data;
socket.emit("response", data);
}
app.post("/emit/:event", function(req, res) {
var event = req.params.event;
switch (event) {
case "echo":
var a = {
key: req.param("key"),
data: req.param("data")
}
echo_handler(a);
break;
}
});
io.sockets.on("connection", function(socket) {
socket.on("connect", function(data) {
sockets[data.key] = socket;
});
socket.on("echo", echo_handler);
});
Another way to do this will be to switch to Sockjs and use their patch.
If someone have better solution for Socket.IO it will be appreciated, because I'm already deep into the project and it's too late to switch Socket.IO for Sockjs, and this solution is not to my liking :( .