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!
Related
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.
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
I am trying to set up a basic chat app with node.js/express/socket.io but for some reason when the client sends message (this works, another client will get the message) it also refreshes the client and the url goes from localhost:3000 to localhost:3000/? (adds /? to end, i don't know what this means). I cant find anything wrong in my code after looking at it for hours. I have:
server.js:
let app = require('express')();
let http = require('http').Server(app);
let io = require('socket.io')(http);
let port = process.env.PORT || 3000;
app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html') });
http.listen(port,() => { console.log('listening on *:' + port) });
io.on('connection', socket => {
socket.on('chat', text => {
io.sockets.emit('chat', `<p>${text}</p>`);
});
});
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<style>
.chat_view{
height: 300px;
width: 200px;
border: 5px ridge black;
overflow-y: scroll;
}
</style>
</head>
<body>
<div class="chat" id="chat">
<div class="chat_view" id="chat_view">
</div>
<form id="chat_form">
<input type="text" title="chat_input" id="chat_input" style="width: 206px">
</form>
</div>
<script>
let socket = io();
$('#chat_form').submit( () => {
let text = $('#chat_input').val();
socket.emit('chat', text);
});
socket.on('chat', text => {
let chat_view = document.getElementById('chat_view');
chat_view.innerHTML += text;
chat_view.scrollTop = chat_view.scrollHeight;
});
</script>
</body>
</html>
and package.json:
{
"name": "RatScrew",
"version": "0.0.1",
"dependencies": {
"express": "^4.15.3",
"socket.io": "^2.0.2"
}
}
If you're listening to the submit event, that means the form will actually try and POST to the server (which will in your case refresh the screen). If you're using JavaScript to communicate with the server and don't need the form data to get posted by the browser directly, just return false from your callback. Some browsers also want you to call e.preventDefault() as well.
Change your code to:
$('#chat_form').submit((event)=>{
event.preventDefault();
let text = $('#chat_input').val();
socket.emit('chat', text);
});
The default method used when submiting the form is the GET method, which makes the server send index.html again and the page refreshes.
You may want to have a look at https://www.w3.org/TR/html401/interact/forms.html
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>
I'm starting playing with node.js and as everybody, I want do a chat.
My idea is run node.js with socket.io in the port 9090, for example, and my client html in the port 8080. My html client will be served independent.
My server:
var sys = require('sys');
var express = require('express');
var io = require('socket.io');
var app = express.createServer();
app.listen(8080);
var socket = io.listen(app);
socket.on('connection', function (client) {
client.on('message', function (msg) {
socket.broadcast(msg);
});
client.on('disconnect', function () {
});
});
My client:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="http://cdn.socket.io/stable/socket.io.js"></script>
<script>
$(document).ready(function () {
var socket = new io.Socket("localhost", {port: 8080});
socket.on('connect', function () {
socket.send('A client connected.');
});
socket.on('message', function (message) {
$('div#messages').append($('<p>'), message);
});
socket.on('disconnect', function () {
console.log('disconnected');
});
socket.connect();
$('input').keydown(function (event) {
if(event.keyCode === 13) {
socket.send($('input').val());
$('input').val('');
}
});
});
</script>
</head>
<body>
<input type="text" style="width: 300px;" />
<div id="messages" style="border:solid 1px #000;"> </div>
</body>
</html>
I'm running in ubuntu 11.04 with node.js v0.4.10.
The server works fine, but the client can't do connection, in the console.log on google Chrome I received this message:
XMLHttpRequest cannot load http://localhost:8080/socket.io/xhr-polling//1311465961485. Origin http://localhost is not allowed by Access-Control-Allow-Origin.
The server.js is in a folder in /var/www/cliente/chat/public.
What's the problem?
Your client code is not actually being served from port 8080 as you want.
var sys = require('sys');
var express = require('express');
var io = require('socket.io');
var app = express.createServer();
app.listen(8080);
app.use(express.static(__dirname));
app.get('/', function(req, res){
res.render('index.html', { title: 'Chat' });
});
var socket = io.listen(app);
socket.on('connection', function (client) {
client.on('message', function (msg) {
socket.broadcast(msg);
});
client.on('disconnect', function () {
});
});
This should fix your Access-Control-Allow-Origin errors. Execute node server.js and connect to http://localhost:8080. A couple additional notes:
Make sure you have installed socket.io 0.6.x since that's what you are including in your html file. 0.7.x is backwards incompatible.
With this configuration you'll be running socket.io on the same port you are serving your page from (as opposed to 9090).
When I updated my client to:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
<script>
var socket = io.connect("http://localhost", {port: 8080});
socket.on('connect', function () {
socket.send('A client connected.');
});
socket.on('message', function (msg) {
$('div#messages').append($('<p>'), msg);
});
socket.on('disconnect', function () {
console.log('disconnected');
});
$(document).ready(function(){
$('#btn_send').click(function (event) {
socket.send($('#txt_msg').val());
$('#txt_msg').val('');
});
});
</script>
</head>
<body>
<input type="text" id="txt_msg" style="width: 300px;" /><input type="button" id="btn_send" value="send" />
<div id="messages" style="border:solid 1px #000;"> </div>
</body>
</html>
Everything worked.
I was using a version 0.7 of the socket.io that was the problem: https://github.com/LearnBoost/Socket.IO/wiki/Migrating-0.6-to-0.7
You cannot make AJAX requests to URLs that are not on the same hostname and port as the current page. It's a security restriction in all web browsers.