I want to use nodeJS in my PHP web app. I followed the nodejs tutorial and that works fine when I run on localhost:3000 but I want to run on url like this localhost/final/chat/chat_index.html file. So What I did is following code
chat_index.html
<div id="newUser">
<form id="user">
<input id="username">
<input type="submit">
</form>
</div>
$(document).ready(function(){
var socket = io.connect('http://localhost:3000/final/chat/chat_index.html',
{resource:'https://cdn.socket.io/socket.io-1.2.0.js'});
$('#user').submit(function(){
socket.emit('new user', $('#username').val());
});
}); // document.ready ends here
</script>
index.js This is server side JS file
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/final/chat/chat_index.html', function(req, res){
res.sendFile(__dirname + '/chat_index.html');
});
io.on('connection', function(socket){
console.log('connected user');
socket.on('new user', function(user){
console.log(user);
});
});
http.listen(3000, function(){
console.log('listening to port');
});
Above chat_index.html page loads which shows the form on it. When I submit some data through this form server side js is not getting the data.
Is something missing in my code or I am doing something wrong in my code.
Thanks in advance
If you wish to run socket on an specific route, you can use room/namespace
http://socket.io/docs/rooms-and-namespaces/#
Example ( server )
var finalChat = io.of("/final/chat");
finalChat.on('connection', function(socket){
console.log('connected user');
socket.on('new user', function(user){
console.log(user);
});
});
If you want Independence private chat rooms, you may want to use id base socket rooms
Which version of express are you using? I believe in express 4 it should be:
var http = require('http').createServer(app);
On the client side could you also try using:
var socket = io.connect();
then load the resource in as a script tag?
Related
Aim: To make the chat message the user entered to appear in the console (terminal). It currently isn't logging anything and I don't know how to debug this problem. Please keep in mind that I'm a beginner to NodeJS and know probably only the basics.
Server-side NodeJS code
const http = require("http");
const host = 'localhost';
const port = 8000;
const express = require('express');
const app = express();
app.use(express.static('./'));
const socketIO = require("socket.io");
// creating the server and starting it on port 8000
const server = http.createServer(app);
server.listen(port, host, () => {
console.log(`Server is running on http://${host}:${port}`);
});
// making io object
const io = socketIO(server, {cookie: false});
// listening to connections to the server
io.on('connection', (socket) => {
console.log('a user connected');
// chat message coming to server
socket.on("details", (chatBundle) => {
console.log(join(chatBundle[0], ": ", chatBundle[1]));
});
});
Client-side HTML code
<!DOCTYPE html>
<html>
<body>
<h1>CHAT ROOM</h1>
<form onsubmit="return sendServer()">
<label for="name">Name:
<input id="name" name="name" type="text">
</label>
<label for="text">Message:
<input id="text" name="text" type="text">
</label>
<input type="submit" id="send" >
</form>
<script src="/Users/chanson/node_modules/socket.io/client-dist/socket.io.js">
</script>
<script>
const chatmsg = "details"; // added
const socket = io(); // added
function sendServer(){
var sender = document.getElementById("name");
var text = document.getElementById("text");
var tempArray = [sender, text]
socket.emit(chatmsg, tempArray)
return false; // added
};
</script>
</body>
</html>
Please help me debug this code.
in your client file import the socket io like this:
<script src="/socket.io/socket.io.js">
instead of
<script src="/Users/chanson/node_modules/socket.io/client-dist/socket.io.js">
as by default, the Socket.IO server exposes a client bundle at /socket.io/socket.io.js.
Also make sure you are hosting the client file from you server's static resources or other wise like so:
// creating the server and starting it on port 8000
app.get('/', (req, res)=>{
res.sendFile(path.join(__dirname, 'public', 'index.html'))
})
const server = http.createServer(app);
server.listen(port, host, () => {
console.log(`Server is running on http://${host}:${port}`);
});
Also in you client file's sendServer function correct the following lines:
var sender = document.getElementById("name").value;
var text = document.getElementById("text").value;
use .value to capture the user input
I have been working on node.js project. my requirement is I want to load.txt file on browser. when I change and save this file, content should be updated. Browser should be auto refresh.
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
index.js
app.get('/', function(req, res){
res.sendFile(__dirname + '/demo.txt');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
var io = require('socket.io')(80);
var fs = require('fs');
fs.watchFile('message.text', (curr, prev) => {
console.log(`the current mtime is: ${curr.mtime}`);
console.log(`the previous mtime was: ${prev.mtime}`);
// file changed push this info to client.
io.emit('fileChanged', 'yea file has been changed.');
});
index.html
<script>
var socket = io();
socket.on('fileChanged', function(msg){
alert(msg);
});
First of all you can do this with two action:
1. Watch file change on server-side. And push info to client
You can watch file with node.js.
var app = require('express')();
var http = require('http').Server(app);
app.get('/', function(req, res){
res.sendFile(__dirname + '/cluster.json');
});
const io = require('socket.io')(http);
io.on('connection',function (client) {
console.log("Socket connection is ON!");
});
http.listen(80, function(){
console.log('listening on *:80');
});
var fs = require('fs');
fs.watchFile('cluster.json', function(curr, prev){
// file changed push this info to client.
console.log("file Changed");
io.emit('fileChanged', 'yea file has been changed.');
});
2. Catch "file changed" info and refresh page on client side
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script type="text/javascript" src="node_modules/socket.io-client/dist/socket.io.js"></script>
<script>
var socket = io("http://localhost:80");
socket.on('fileChanged', function(msg){
alert(msg);
});
</script>
</body>
</html>
The best way to do this is using WebSockets. A very good package to work with WebSockets is Socket.io, and you can use something like chokidar or the native function fs.watch to watch the file changes and then emit an messsage.
Or if you trying to do this only for development purposes, you should check webpack, gulp or other task runner that have built-in functions to do this.
Do polling for the file using Ajax. Your server could respond with {changes: '{timestamp-of-file-modify}'}. Now check if your last seen change time differs from response time.
If there is changes: window.location.reload
I've been trying to get familiarized with socket.io so use it in a real time app. I went through the basic example, a chat room, then I used ngrok to do a test with more than one client and it's all good. Now I'm looking to use TAFFY to save a log of the conversation on deploy it to a new user that connects to it so I added another emmit to send that log, and this particular emmit doesn't seem to ever trigger the on sentence in the client's side.
These are the server instructions
io.on('connection', function(socket){
console.log("someone connected");
var chatLog={log:[]};
log().each(function (iter){ //this is the taffy var
chatLog.log.push({"usr":iter.usr,"msg":iter.msg});
});
var stringLog=JSON.stringify(chatLog);
console.log(stringLog);
socket.emit('cargaLog', stringLog);// THIS is the naughty emmit
socket.on('chat message', function(msg){
var mensaje=JSON.parse(msg);
log.insert({"usr":mensaje.usr,
"msg":mensaje.msg
});
io.emit('chat message', mensaje.usr.toUpperCase()+" dice: "+mensaje.msg);
});
});
Client's side
$(function () {
var socket = io();
socket.on('cargaLog', function(log){
alert(log); //this never happens
console.log(log);
});
$('form').submit(function(){
var mensaje=$('#m').val();
var json='{"usr":"'+person+'","msg":"'+mensaje+'"}';
socket.emit('chat message', json);
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
var html='<li><img src="defaultUsrImg.png" alt="Usr_img" heigth="40" width="40">'+(msg)+'</li>';
$('#messages').append(html);
window.scrollTo(0, document.body.scrollHeight);
});
});
I've been staring at this code for a while and none of the solutions that worked with other people work for me (i.e. using io.connect() or io.connect('http://0.0.0.0:8080') on the client's side or having an emmit from the client that asks for the server emmit to be triggered).
Anyone has any idea why this happens?
Altenatively, anyone have any idea that could help me troubleshoot this better?
Other details are:
Running windows 10
Node version 8.2.1
socket.io version 2.0.3
This how I use the node requires:
var TAFFY = require('taffy');
var express=require('express');
var app = express();
var http = require('http');
var path=require('path');
var port = process.env.PORT || 3000;
var server= http.createServer(app).listen(port);
var io = require('socket.io').listen(server);
var log=TAFFY({"usr":"SERVER",
"msg":"WELCOME"
});
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
Client html code (only the boddy because mt html includes and it would bee way too long
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script type="text/javascript" src="./socket.io/socket.io.js"></script>
<script src="jquery-3.2.1.min.js"></script>
<!-- <script src="/mensajes.js"></script> THIS IS THE OLD CODE-->
<script >
var person = prompt("Introduce tu nombre o seudonimo", "anon"); //THIS IS THE WORKING CODE
if(person === null || person===""){
alert("Necesitas un nombre para participar");
}
else{
$(function () {
var socket = io();
socket.emit('ia iege',person);
socket.on('usrConectado',function(usr){
var html='<li><h6>'+(usr)+' se ha conectado</h6></li>';
$('#messages').append(html);
window.scrollTo(0, document.body.scrollHeight);
});
$('form').submit(function(){
var mensaje=$('#m').val();
var json='{"usr":"'+person+'","msg":"'+mensaje+'"}';
socket.emit('chat message', json);
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
var html='<li><img src="https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/419693/pedreiro-1500067445.PNG" alt="Usr_img" heigth="40" width="40">'+(msg)+'</li>';
$('#messages').append(html);
window.scrollTo(0, document.body.scrollHeight);
});
socket.on('cargaLog', function(log){
console.log(log);
var oldLog=JSON.parse(log);
cargaLog(oldLog);
});
});
function cargaLog(newLog){
//newLog is an object
newLog.log.forEach(function(iter){
var msg=iter.usr.toUpperCase()+' dijo: '+iter.msg;
var html='<li><img src="https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/419693/pedreiro-1500067445.PNG" alt="Usr_img" heigth="40" width="40">'+(msg)+'</li>';
$('#messages').append(html);
window.scrollTo(0, document.body.scrollHeight);
});
}
}
</script>
</body>
I reduced your code down to just the basics and I'm getting the message just fine that you were having trouble with. Here's the reduced code that works just fine:
Server code:
var express = require('express');
var app = express();
var http = require('http');
var path = require('path');
var port = process.env.PORT || 3000;
var server= http.createServer(app).listen(port);
var io = require('socket.io').listen(server);
app.get('/', function(req, res){
res.sendFile(__dirname + '/s1.html');
});
io.on('connection', function(socket) {
console.log("someone connected");
var chatLog = {log: [{usr: "someuser", msg: "somemsg"}]};
var stringLog = JSON.stringify(chatLog);
console.log(stringLog);
socket.emit('cargaLog', stringLog); // THIS is the naughty emmit
});
Client Code:
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
<script>
function dbg(x) {
let str = x;
if (typeof x === "object") {
str = JSON.stringify(x);
}
$("#log").append("<div>" + str + "</div>");
}
$(function() {
var socket = io();
socket.on('cargaLog', function(log) {
dbg(log);
});
});
</script>
</head>
<body>
Empty Content, waiting for message to arrive.
<div id="log"></div>
</body>
</html>
When I load the page, the browser immediately displays the cargaLog message that you were having trouble with. I would suggest that you backtrack to something super simple like this until you prove it works and then add things back one at a time until you find what is introducing the problem. If this code does not work for you, then you must have something goofed up in your environment and I'd probably do a reinstall of various components (socket.io, node.js, express, etc...).
Try
socket.emit('chat message' , { usr: person, msg: mensaje});
I think you can try to look at this repository https://github.com/egin10/socket-chat-example/blob/master/app.js for your server side.
and you can try this one for your client side https://github.com/egin10/socket-chat-example/blob/master/chat.html
Note: Just remember about socket.on(params, callback), it's for fetching data from emmiter, and io.emit(params, obj) on server side is for emmiting data.
so, you must make sure about what is your emmiting to server or client and what's your fetching (socket.on()) from serveror client must have same params.
and you must make sure about your object is var chatLog={log:[]};. if you want to get log, you must do like this chatLog.log.
It's work to me. i hope it can help you.
I recently started using Socket.io, and node.js as a result, and I am kind of stuck. I do not even know if this is a practical solution for my application, but hopefully someone can help.
All I have here is a webpage with a checkbox, which reports it's status to the node console, and then when a TCP client connects, it receives the status as well.
I am wondering how I would go about making this event continuous, so that the TCP client constantly receives updates on the status of the checkbox.
If anyone has any idea, please let me know, and sorry for the long code...
Server Code:
var net = require('net');
var app = require('express')(); <!-- These are mandatory variables -->
var http = require('http').Server(app);
var io = require('socket.io')(http);
var HOST = 'localhost';
var PORT = 4040;
GLOBAL.MYVAR = "Hello world";
var server = net.createServer();
server.listen(PORT, HOST);
app.get('/', function(req, res){ <!-- This sends the html file -->
//send the index.html file for all requests
res.sendFile(__dirname + '/index.html');
});
http.listen(3001, function(){ <!-- Tells the HTTP server which port to use -->
console.log('listening for HTTP on *:3001'); <!-- Outputs text to the console -->
console.log('listening for TCP on port ' + PORT);
});
<!-- everything below this line are actual commands for the actual app -->
io.on('connection', function(socket) // Opens the socket
{
socket.on('checkbox1', function(msg){ // Creates an event
console.log(msg); // displays the message in the console
MYVAR = msg; // Sets the global variable to be the contents of the message recieved
});
});
server.on('connection', function(socket){ // Opens the socket for the TCP connection
socket.write(MYVAR);
}).listen(PORT, HOST);
Client code:
<!doctype html>
<html>
<head>
<title>Socket IO Test</title>
<form action="">
<input type='checkbox' onclick='checkbox1(this);'>Checkbox1</label>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
var number = 0;
function checkbox1(cb) {
socket.emit('checkbox1', 'checkbox 1 = ' + cb.checked);
return false;
}
</script>
</body>
</html>
Cheers
I believe the issue here is that you don't have a way to reference the TCP socket. Once you do have a reference it is as easy as receiving a message and sending it.
This will work for a single client.
var net = require('net');
var app = require('express')(); <!-- These are mandatory variables -->
var http = require('http').Server(app);
var io = require('socket.io')(3000);
var s;
var HOST = 'localhost';
var PORT = 4040;
GLOBAL.MYVAR = "Hello world";
var server = net.createServer();
server.listen(PORT, HOST);
app.get('/', function(req, res){ <!-- This sends the html file -->
//send the index.html file for all requests
res.sendFile(__dirname + '/index.html');
});
http.listen(3001, function(){ <!-- Tells the HTTP server which port to use -->
console.log('listening for HTTP on *:3001'); <!-- Outputs text to the console -->
console.log('listening for TCP on port ' + PORT);
});
<!-- everything below this line are actual commands for the actual app -->
io.on('connection', function(socket) // Opens the socket
{
socket.on('checkbox1', function(msg){ // Creates an event
console.log(msg); // displays the message in the console
MYVAR = msg; // Sets the global variable to be the contents of the message recieved
s.write(MYVAR, 'utf-8');
});
});
server.on('connection', function(socket){ // Opens the socket for the TCP connection
s = socket;
s.write(MYVAR, 'utf-8');
}).listen(PORT, HOST);
This will work for multiple clients.
var net = require('net');
var app = require('express')(); <!-- These are mandatory variables -->
var http = require('http').Server(app);
var io = require('socket.io')(3000);
var sockets = [];
var HOST = 'localhost';
var PORT = 4040;
GLOBAL.MYVAR = "Hello world";
var server = net.createServer();
server.listen(PORT, HOST);
app.get('/', function(req, res){ <!-- This sends the html file -->
//send the index.html file for all requests
res.sendFile(__dirname + '/index.html');
});
http.listen(3001, function(){ <!-- Tells the HTTP server which port to use -->
console.log('listening for HTTP on *:3001'); <!-- Outputs text to the console -->
console.log('listening for TCP on port ' + PORT);
});
<!-- everything below this line are actual commands for the actual app -->
io.on('connection', function(socket) // Opens the socket
{
socket.on('checkbox1', function(msg){ // Creates an event
console.log(msg); // displays the message in the console
MYVAR = msg; // Sets the global variable to be the contents of the message recieved
for (var i = 0; i < sockets.length; i++) {
if(sockets[i]) {
sockets[i].write(MYVAR, 'utf-8');
}
}
});
});
server.on('connection', function(socket){ // Opens the socket for the TCP connection
sockets.push(socket);
socket.write(MYVAR, 'utf-8');
}).listen(PORT, HOST);
I have multiple buttons with an attribute called groupName. They look like this:
SCENE I
SCENE II
SCENE III
I'm trying to figure out how to get socket.io to emit the link's groupName value when clicked. So when the first link is clicked, socket.io would emit "groupName - SCENE_I"
How could this be accomplished?
It seems you want something similar to a chat -- where a click on a link acts as a user sending a message to the server, and the server would emit that to a room (to other users, I suppose?)
If that's the case, you should take a look at this example: http://socket.io/get-started/chat/
You would do something like this on the client side:
<html>
<head>
</head>
<body>
SCENE I
SCENE II
SCENE III
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
$(document).ready(function(){
var socket = io();
// listen to server events related to messages coming from other users. Call this event "newClick"
socket.on('newClick', function(msg){
console.log("got new click: " + msg);
});
// when clicked, do some action
$('.fireGroup').on('click', function(){
var linkClicked = 'groupName - ' + $(this).attr('groupName');
console.log(linkClicked);
// emit from client to server
socket.emit('linkClicked', linkClicked);
return false;
});
});
</script>
</body>
</html>
On the server side, still taking the chat idea into consideration:
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');
});
io.on('connection', function(socket){
// when linkClicked received from client...
socket.on('linkClicked', function(msg){
console.log("msg: " + msg);
// broadcast to all other users -- originating client does not receive this message.
// to see it, open another browser window
socket.broadcast.emit('newClick', 'Someone clicked ' + msg) // attention: this is a general broadcas -- check how to emit to a room
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});