Socket.IO Chat not sending and/or recieving messages - javascript

I have followed a tutorial for socket.io chat:
https://www.youtube.com/watch?v=pNKNYLv2BpQ
In the tutorial video it works fine however mine does not work at all. The messages do not seem to be sent or received by either the server or the client
This is my app.js run on the server side with node
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(3000);
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket) {
socket.on('send message', function(data) {
io.sockets.emit('new message', data);
});
});
This is my index.html client
<html>
<head>
<title>Chat with socket.io and node.js</title>
<style>
#chat
{
height: 500px;
}
</style>
</head>
<body>
<div id="chat"></div>
<form id="send-message">
<input size="35" id="message"></input>
<input type="submit"></input>
</form>
<script src="http://code.jquery.com/jquery-latest.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 message', $messageBox.val());
$messageBox.val('');
});
socket.on('new message', function(data) {
$chat.append(data + "<br/>");
});
});
</script>
I suppose it is a simple error that I have overlooked but I'm stumped at the moment, any ideas ??? Also if you require additional information please say so :)

create one index.html file
index.html
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
</html>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
index.js
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){
console.log('a user connected');
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
For more information click here

Related

How can I create a separate client.js file with socket.io?

How should the chat application example (described on https://socket.io/get-started/chat/) look if I wanted the client script that currently exists in the index.html file, to exist in a separate client.js file? Note: In this example tutorial, I'm at the part where I'm trying to get a user connected to appear when refreshing the web page, but this is not working correctly.
I've tried including <script src="client.js"></script> in the head section of my index.html file, and then
const io = require('socket.io-client');
var socket = io();
in my client.js file, but it does not work. When I run node server.js, the chat application design displays on the web page correctly, and I show the listening on *:3000 text in the terminal, but not the a user connected text which should appear when I refresh the web page.
My server.js, index.html, and client.js files are all in the top level of the directory, and are as follows:
server.js
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html'); // Based on some research, I feel that the problem might
// be here, where I'm sending just a file, not a directory?..
});
io.on('connection', (socket) => {
console.log('a user connected');
});
http.listen(3000, () => {
console.log('listening on *:3000');
});
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Chat Application</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: 0.5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
<script src="client.js"></script>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
</html>
client.js
// I am also unsure if the following is correct...
const io = require('socket.io-client');
var socket = io();
This is an old question but still an issue with the socket.io example code. I was able to figure it out. The issue is that the file-system works differently when running whatever server (including localhost).
In short, to resolve this issue, in index.js (or what is called server.js in OP's question), replace:
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
with
app.use(express.static(__dirname));
app.get('/', (req, res) => {
});
(of course feel free to fill the app.get function later if needed.

is there a way to automatically scroll to the last item after appending from a javascript event to an unordered list?

I am developing a simple chat app using javascript and socket.io with node.js
Everything works well, except when chat messages are appended when a chat message is received, the list of chat messages grows but stays at the top instead of scrolling to the bottom to show the last message that arrived.
I have tried all suggestions but the list keeps appending the messages but stays on the top showing the oldest message first and the new ones are not shown unless I manually scroll the list with the mouse
Your help will be greatly appreciated.
Thank you
here is the code:
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0;}
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</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 src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
var socket = io();
$('form').submit(function(e){
e.preventDefault(); // prevents page reloading
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
});
</script>
</body>
</html>
and here is the server code run with node.js
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
console.log('about to send:'+__dirname + '/index.html');
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
I have a chat app that uses this jQuery code to smoothly scroll to the bottom of the document. The animation takes 800 milliseconds.
// scroll to bottom of display
$('html, body').animate({scrollTop:$(document).height()}, 800);
Docs for jQuery.animate() and Element.scrollTop.
use scrollTop to go after add new one
<script>
$(function () {
var socket = io();
$('form').submit(function(e){
e.preventDefault(); // prevents page reloading
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
var ul= document.getElementById("messages");
ul.scrollTop = ul.scrollHeight;
});
});
</script>

How can I get rid of the "undefined" in this Node.js chat

I'm new with Node.js and Socket.IO and I can't seem to figure out why I keep getting "undefined", I'm trying to get a username in front of the message which it does, but I cant seem to get rid of that nasty undefined.
Here is my index.js:
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){
console.log('a user connected');
io.emit('chat message','User Connected');
socket.on('disconnect', function(){
io.emit('chat message','User Disconnected');
console.log('user disconnected');
});
});
http.listen(13280, function(){
console.log('listening on *:13280');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
});
io.on('connection', function(socket){
socket.on('chat message', function(msg,username){
io.emit('chat message',username + msg);
});
});
and here my index.html
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
.name {margin-bottom: 40px;}
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</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 src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var name = prompt("Choose a username","username");
var halveusername = "[" + name;
var username = halveusername + "] ";
var socket = io();
$('form').submit(function(){
socket.emit('chat message',username + $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
</body>
</html>
You are probably better off sending a json object as the message if it contains multiple values - it gives you more flexibility and will fix your error in any case.
Try this
in index.js
io.on('connection', function(socket){
socket.on('chat message', function(message){
io.emit('chat message', message);
});
});
and in index.html
$('form').submit(function(){
var message = {
username: username,
text: $('#m').val()
};
socket.emit('chat message', message);
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg.username + msg.text));
});

How to append data to a div in client side When server is pushing

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');
});
io.on('connection', function(socket){
for(i=0; i<10; i++){
io.emit('notification', i);
}
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
<body>
<style type="text/css">
.chatting {
width: 40px;
height: 40px;
border-radius: 50%;
margin-left: auto;
margin-right: auto;
background-color: #a6a6a6;
}
</style>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
socket.on('notification', function(msg){
alert(msg);
});
</script>
<div class = chatting></div>
</body>
I am just trying to append data to a div in client side when the server is pushing some value. How to do that. Here is my code. The alert is working fine. But I need the Numbers are inserted to the div. Every time server pushing, the number should be changed automatically, like notifications on Facebook.
Thank you.
<script>
var socket = io();
function appendNotification(notification){
document.getElementById("notifications").innerHTML = "<div>" + notification + "</div>";
}
socket.on('notification', function(msg){
appendNotification(msg);
});
</script>
ADD the id to your html
<div class="chatting" id="notifications"></div>
Try with this on your code. I hope this help.
<script>
var socket = io();
socket.on('notification', function(msg){
var div = document.getElementsByClassName('chatting');
div.innerHTML += msg;
});
</script>
Try it :
<script>
$(document).ready(function(){
var socket = io();
socket.on('notification', function(msg){
alert(msg);
$('.chatting').text(msg);
});
});
</script>
<body>
<style type="text/css">
.chatting {
width: 40px;
height: 40px;
border-radius: 50%;
margin-left: auto;
margin-right: auto;
background-color: #a6a6a6;
}
</style>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<div class="chatting"></div>
</body>

Installing socket io for node.js on Windows 7

When I run the node server, the console indicates "info - socket.io started". However, it never detects a connection from the client side. I believe it is an issue with the installation of socket.io as I am running a Windows 7 machine...
When I attempt to connect to the server from the client side my server console indicates "debug - served static content /lib/socket.io.js".
Anyone have any suggestions how I can get socket io to succesfully connect from the client side on my Windows 7 machine?
Right now, I have the socket.io folder located in the following directory:
nodejs/node_modules/socket.io/
I have the following code on the server side for a tcp server in node:
var http = require('http'),
sys = require('util'),
fs = require('fs'),
io = require('socket.io');
console.log('Creating server...');
var server = http.createServer(function(request, response) {
response.writeHead(200, {
'Content-Type': 'text/html'
});
var rs = fs.createReadStream(__dirname + '/template.html');
sys.pump(rs, response);
});
var socket = io.listen(server);
socket.on('connection', function(client) {
var username;
console.log('New client connected.');
client.send('Welcome to this socket.io chat server!');
client.send('Please input your username: ');
client.on('message', function(message) {
if (!username) {
username = message;
client.send('Welcome, ' + username + '!');
return;
}
socket.broadcast(username + ' sent: ' + message);
});
});
server.listen(20000);
This is the code on the client side:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chat</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript" src="http://localhost:20000/socket.io/lib/socket.io.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var entry_el = $('#entry');
var socket = new io.Socket('localhost', {port: 20000});
socket.connect();
console.log('connecting...');
socket.on('connect', function() {
console.log('connect');
});
socket.on('message', function(message) {
var data = message.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");
$('#log ul').append('<li>' + data + '</li>');
window.scrollBy(0, 1000000000000000);
entry_el.focus();
});
entry_el.keypress(function(event) {
if (event.keyCode != 13) return;
var msg = entry_el.attr('value');
if (msg) {
socket.send(msg);
entry_el.attr('value', '');
}
});
});
</script>
<style type="text/css">
body {
background-color: #666;
color: fff;
font-size: 14px;
margin: 0;
padding: 0;
font-family: Helvetica, Arial, Sans-Serif;
}
#log {
margin-bottom: 100px;
width: 100%;
}
#log ul {
padding: 0;
margin: 0;
}
#log ul li {
list-style-type: none;
}
#console {
background-color: black;
color: white;
border-top:1px solid white;
position: fixed;
bottom: 0;
width: 100%;
font-size: 18px;
}
#console input {
width: 100%;
background-color: inherit;
color: inherit;
font-size: inherit;
}
</style>
</head>
<body>
<h1>Chat</h1>
<div id="log"><ul></ul></div>
<div id="console">
<input type="text" id="entry" />
</div>
</body>
</html>
Thanks!
Your socketio js should be inside the following path
http://{host:port}/socket.io/socket.io.js
In your case you need to include as follows
<script type="text/javascript" src="http://localhost:20000/socket.io/lib/socket.io.js"></script>

Categories

Resources