Cant get response making real time chat with nodejs - javascript

I'm trying to make real time chat with nodeJs.. But i have some problems.
The console.log in the part of
io.on('connection', function(socket)
{
console.log("A user connected");
});
does not console.log at all.
When I got stuck i was searching for a guide.. I build it almost the same as in the guide.
Here is my html page:
<!doctype html>
<html>
<head>
<title>
Socket.IO chat
</title>
<link rel="stylesheet" href="./CSS/style.css" media="screen" title="no title" charset="utf-8">
</head>
<body>
<ul id="messages">
</ul>
<form action="">
<input id="m" autocomplete="off" />
<button>
Send
</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
</body>
</html>
And here my js file:
var app = require("express")(),
http = require("http").Server(app),
io = require("socket.io")(http),
port = 3000;
app.get('/', function(req, res)
{
res.sendFile(__dirname + "./index.html");
});
io.on('connection', function(socket)
{
console.log("A user connected");
});
http.listen(port, function()
{
console.log('Listening on port: ' + port);
});
my file structure:
^because I think it has something to do with the linking between the pages.
I am using this guide: http://socket.io/get-started/chat/
Thanks in advance,
I hope to get some answers so i can go on with this :)
Cheers

It looks like your HTML page is missing the server URL:
var socket = io.connect("http://" + window.location.host); //e.g. http://localhost:3000

Related

getting error in <script src = "/socket.io/socket.io.js"></script>

i know this question has been asked many times buit i have spent 3 hours trying to figure it out but to no avail. i am getting error in GET
http://localhost:3000/socket.io/socket.io.js net::ERR_ABORTED
and io is not defined. any help would be highly appreciated. i am typing extra coz my post requires more details ..........
public/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="styles.css" />
</head>
<body>
<div id="wrapper">
<div class="form_div" id ="login">
<p class="form_label">LOGIN FORM</p>
<form method="post" action="">
<p><input id ="user-name" type="text" placeholder="Enter user-name"></p>
<p><input id = "pass-word" type="password" placeholder="**********"></p>
<p><input id = "submit" type="submit" value="LOGIN"></p>
</form>
</div>
<br>
<br>
<br>
<div class="form_div" id = "signup">
<p class="form_label">SIGNUP FORM</p>
<form method="post" action="">
<p><input id ="signupusername" type="text" placeholder="Enter
Name"></p>
<p><input id = "signuppass" type="password"
placeholder="**********"></p>
<p><input id ="register" type="submit" value="SIGNUP"></p>
</form>
</div>
</div>
<script src = "index.js"></script>
<script src = "/socket.io/socket.io.js"></script>
public/index.js
var socket = io();
var loginDiv = document.getElementById('login');
var Username = document.getElementById('user-name');
var loginPassword = document.getElementById('pass-word');
var login = document.getElementById('submit');
var SignUpDiv = document.getElementById('signup');
var Signupuser = document.getElementById('signupusername');
var Signuppass = document.getElementById('signuppass');
var signup = document.getElementById('register');
login.onclick = function(){
socket.emit('login-details',{
username:Username.value,
password:loginPassword.value
});
}
signup.onclick = function(){
socket.emit('signup-details',{
newuser:Signupuser.value,
newuserpassword:Signuppass.val
});
}
socket.on('login-response',(data)=>{
if(data.success){
alert('login Successful');
}
else{
alert('login Unsuccessful');
}
});
socket.on('signup-response',(data)=>{
if(data.success){
alert('Signup Successful')
}
else{
alert('Signup-Successful')
}
});
server/server.js
var express = require('express');
var path = require('path');
var http = require('http');
var MongoClient = require('mongodb').MongoClient;
const socketIO = require('socket.io');
var app = express();
var server = http.createServer(app);
const port = process.env.PORT ||3000;
var io = socketIO(server);
const pathjoin = path.join( __dirname ,'../public');
app.use(express.static(pathjoin));
MongoClient.connect('mongodb://localhost:27017/DETAILS',(err,client)=>{
if(err){
return console.log('unable to connect to the MongoDb server');
}
const db =client.db('DETAILS');
console.log('connected to the MongoDb server');
});
io.on('connection',(socket)=>{
console.log('new user connected');
//login
socket.on('login-details',(data)=>{
db.collection('user-
details').find({username:data.username,password:data.password},
(err,result)=>{
if(err) throw err;
socket.emit('login-response',{
success:true
});
});
});
//signup
socket.on('signup-details',(data)=>{
db.collection('user-
details').insert({username:data.newuser,password:data.newuserpassword},
(err,result)=>{
if(err) throw err;
socket.emit('signup-response',{
success:true
});
});
});
});
app.listen(port,()=>{
console.log('server started');
});
In your server/server.js, at the very end of your codes, change app.listen() to server.listen(), because express requires that you instantiate a HTTP server in Socket.IO.
This should be your new ending part of server.js
server.listen(port,()=>{
console.log('server started');
});
In index.html
<script src = "index.js"></script>
<script src = "/socket.io/socket.io.js"></script>
change it to
<script src = "/socket.io/socket.io.js"></script>
<script src = "index.js"></script>
Swap the includes in html .First you need to include socket.io and then use it in index.js.
In index.js
var socket = io.connect();
error solved. It was a silly mistake! since socket.io uses http server and not the express server. so i did create a http server but at during listening to a port i use express like app.listen(). In server/server.js it should be:
server.listen(port,()=>{ console.log('server started');});
Try this. Change,
<script src = "/socket.io/socket.io.js"></script>
to
<script src="http://YOUR_IP_ADDRESS/socket.io/socket.io.js"></script>

socket io not giving the desired output

I have created a index.js which loads index.html using sockets.
the server is running successfully and also the index.html page loads. but cant append the written text in the div.
index.js
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(3000, function() {
console.log("SERVER CREATED WITH PORT 3000");
});
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket) {
socket.on('send', function(data) {
io.sockets.emit('new', data);
});
});
index.html
<html>
<head>
<title>chat</title>
<style>
#chat {
height: 500px;
}
</style>
</head>
<body>
<div id="chat"></div>
<form id="send-message">
<input id="message" />
<input type="submit" />
</form>
<h1>Working</h1>
<script src="jquery-3.2.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
jQuery(function($) {
var socket = io.connect();
var $messageform = $('#send-message');
var $messagebox = $('#message');
var $chat = $('#chat');
$messageform.submit(function(e) {
e.preventDefault();
socket.emit('send', $messagebox.val());
$messagebox.val('');
});
socket.on('new', function(data) {
$chat.append(data + "<br />");
});
});
</script>
</body>
</html>
These are the files which I have created and want to send the text to all tabs.
The browser just gets refreshed without loading the text when submit is hit.
Please let me know what I am doing wrong.

Socket.emit not going through

index.js
var app = require('express')();
var path = require('path');
var server = require('http').Server(app);
var io = require('socket.io')(server);
var users = [];
connections = [];
server.listen(process.env.PORT || 3000);
app.use(require('express').static(path.join(__dirname)));
console.log('server running');
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
var addedUser = false;
socket.on('new post', function(post){
console.log(post);
socket.emit('posted', data);
});
});
client.js
$(function(){
function submit(){
socket.emit('new post', $("#text").val());
console.log("submitted");
}
function addPost(data){
console.log(2);
var $post = $('<p></p>').text(data);
console.log($post);
$("#posts").append($post);
}
$("#submit").on("click", function(){
submit();
});
socket.on('posted', function(data){
console.log(1);
addPost(data);
});
});
index.html
<html>
<head>
<title>title</title>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="text">Input</input>
<button id="submit">Submit</button>
<script src="client.js"></script>
<br>
<br>
<br>
<div id="posts"></div>
<script>
var socket = io();
</script>
</body>
</html>
When I start up the server, the console logs "server running" fine. I can't get the submit post button to do anything. None of the debug console messages appear and nothing happens. It's supposed to emit "new post" when the submit button is clicked but it looks as if nothing goes through
I was able to get your code to work on my own computer like this:
index.js
var express = require('express');
var app = express();
var path = require('path');
var server = require('http').Server(app);
var io = require('socket.io')(server);
var users = [];
connections = [];
app.get('/', function(req, res){
res.sendFile(path.join(__dirname, 'index.html'));
});
app.use(express.static(__dirname));
console.log('server running');
io.on('connection', function (socket) {
console.log("connection");
socket.on('new post', function(post){
console.log(post);
socket.emit('posted', post);
});
});
server.listen(process.env.PORT || 3000);
client.js
$(function(){
function submit(){
socket.emit('new post', $("#text").val());
console.log("submitted");
}
function addPost(data){
console.log(2);
var $post = $('<p></p>').text(data);
console.log($post);
$("#posts").append($post);
}
$("#submit").on("click", function(){
submit();
});
socket.on('posted', function(data){
console.log(1);
addPost(data);
});
});
index.html
<html>
<head>
<title>title</title>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="text">Input</input>
<button id="submit">Submit</button>
<script src="/client.js"></script>
<br>
<br>
<br>
<div id="posts"></div>
<script>
var socket = io();
</script>
</body>
</html>
Changes to index.js
Define express variable so it can be reused.
Define app.get() before app.use(express.static(...)) so we're sure to serve index.html with the app.get() and not from the static location.
Change res.sendfile() to res.sendFile()`
Change socket.emit("posted", data) to socket.emit("posted", post).
Move server.listen() to end after everything else is set up.
Remove path.join() from express.static() call since it is not needed there.
Add path.join() to res.sendFile() call for cross platform safety in path building.
Of these, the only one I'm sure was causing an error was #4, the others are good housekeeping.
Changes to client.js
None
Changes to index.html
Change path to client.js to /client.js.
If this code doesn't work on heroku, then you either don't have files positioned in the right directories or heroku is not configured properly to allow your app or socket.io to work properly. If I were you, I would first verify that this code work on your own local computer and only then, go try it on heroku to eliminate variables first.

socket.io rich text editing with Quill

I was trying to implement Quill API with socket.io to build a realtime editor. I was able to get the Delta emitted, but quill.updateContents() does not seems to update the text editor with the emitted Delta op data.
Here is my code:
index.html (client side)
<!DOCTYPE html>
<html>
<head>
<title>Connected Clients</title>
<!--<meta charset="UTF-8"> -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<!--<script type="text/javascript" src="jquery.js"></script> -->
<script src="/socket.io/socket.io.js"></script>
<link href="https://cdn.quilljs.com/1.1.1/quill.snow.css" rel="stylesheet">
<link href="https://cdn.quilljs.com/1.1.2/quill.snow.css" rel="stylesheet">
</head>
<body>
<div id="editor">
<p>Hello World!</p>
<p>Some initial <strong>bold</strong> text</p>
<p><br></p>
</div>
<span id="insertHere"></span>
<script src="https://cdn.quilljs.com/1.1.2/quill.js"></script>
<script>
$(document).ready(function () {
var quill = new Quill('#editor', {
theme: 'snow'
});
var socket = io();
socket.on('updated_para',function(data){
var el = document.getElementById('insertHere');
el.innerHTML = data;
var ops = data;
quill.updateContents(data);
});
quill.on('text-change', function(delta, source) {
var para = quill.getContents();
socket.emit('para',{delta:JSON.stringify(delta.ops)});
});
});
</script>
</body>
</html>
index.js (server side)
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
io.sockets.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
socket.on('para',function(data){
io.emit('updated_para',data.delta);
console.log('message: ' + data.delta);
});
});
I will really appreciate your help!
i think you forget to convert the json code back to an object..
you convert the data before sending to your socket server to a json string. So the date you receive would alway be a string instead of an json.object.
// Replace
var ops = data;
quill.updateContents(data);
// with
var ops = JSON.parse(data);
quill.updateContents(data);
i'm planning to make a similar kind of editor, so i can watch / share code editing.
Kind Regard.

Loading socket.io/socket.io.js into html head returning "ReferenceError: io is not defined"

I am working on a simple socket.io project, and have hit a wall. When I added the script <script src="/socket.io/socket.io.js"></script><script type="text/javascript">var socket = io(); </script> into the head, I was expecting the application to recognize this, but instead I got the error message GET http://localhost:5678/socket.io/socket.io.js and Uncaught ReferenceError: io is not defined in my console. I am using the express framework.
var express = require('express');
var router = express.Router();
var http = require('http').Server(express);
var io = require('socket.io')(http);
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'NodeIM' });
});
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
server = http.listen(3000, function() {
console.log('Listening on port %d', server.address().port);
});
module.exports = router;
HTML:
<html>
<head>
<title>NodeIM</title>
<link rel="stylesheet" href="/stylesheets/style.css">
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript">var socket = io(); </script>
<style type="text/css"></style>
</head>
<body>
<h1>NodeIM</h1>
<p>Welcome to NodeIM</p>
<hr>
<ul id="messages"></ul>
<form id="im_form" action=""><input id="m" autocomplete="off"><button>Send</button></form>
</body>
</html>
NOTE: I've also tried to follow socket.io - ReferenceError: io is not defined and changed my src to src="http://localhost:5678/socket.io/socket.io.js", but it did not fix the issue. I've also tried to use Node.js socket.io.js not found or io not defined, which just showed me another way of requiring socket.io, but doesn't fix the ReferenceError problem I am having
Your usage of /socket.io/socket.io.js for src is correct. However, your setting up of the http server has a typo: var http = require('http').Server(express); should probably be var http = require('http').Server(router);.
As stated in the chat-demo on Socket.io you should put the <script> directly above the closing </body>-tag. Like this:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
</body>

Categories