I'm trying to see express, mongoose and MongoDB work together, in a really simple way. If I can have a box, put my name in there, submit it and have it save to the DB, that's all I need.
I tried doing this from taking pieces of tutorials but I'm stuck. I was trying to do it through a chat and just save every message. If you can get my example to work or have one of your own, either way, It just helps me see something that works.
Then I can have a foundation of what works and can add to it. I see a lot of tutorials and everything else, but not something simple for people, it's always a big project you get lost on somewhere, hopefully, this will be helpful to others too, it's a lot, with everything, with node and all its friends.
With my example, I am not getting any errors, that I see, but there may be some. And I'm looking in DB chat to see the messages using db.messages.find() but there not in there.
HTML:
<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/>");
});
});
var chatSchema = mongoose.Schema({
msg: String,
created: {type: Date, default: Date.now}
});
var Chat = mongoose.model('Message', chatSchema);
var newMsg = new Chat({msg: msg});
newMsg.save(function(err){
if(err) throw err;
});
</script>
</body>
</html>
Server.js
var mongoose = require('mongoose')
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);
});
});
mongoose.connect('mongodb://localhost/chat', function(err){
if(err){
console.log(err);
} else{
console.log('Connected to mongodb!');
}
});
I've tried it and the modified version bellow works! The main changes where putting the mongoose schema code on the server side, and echo back the content of the text box on the server only after a successful save in the Mongo database.
Have a look also at the mean.io site for introduction to the MEAN stack, let me know if you have questions on the code.
Modified server.js:
var mongoose = require('mongoose')
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 + '/test.html');
});
io.sockets.on('connection', function(socket){
socket.on('send message', function(data){
var newMsg = new Chat({msg: '' + data});
console.log('saving newMsg: ' + newMsg);
newMsg.save(function(err){
console.log('saved, err = ' + err);
if(err) throw err;
console.log('echoeing back data =' + data);
io.sockets.emit('new message', data);
});
});
});
var chatSchema = mongoose.Schema({
msg: String,
created: {type: Date, default: Date.now}
});
var Chat = mongoose.model('Message', chatSchema);
mongoose.connect('mongodb://localhost/test', function(err){
if(err){
console.log(err);
} else{
console.log('Connected to mongodb!');
}
});
This is the html page:
<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){
console.log('Received data: ' + data);
$chat.append(data + "<br/>");
});
});
</script>
</body>
</html>
Related
When a user clicks an html button (#new) I want to store their socket.id into an array (userQueue) on my node server but I'm having trouble figuring out how to do this. Do I need to set up a post request or is there a way through socket.io?
App.js (Server):
// App setup
var express = require('express'),
socket = require('socket.io'),
app = express(),
bodyParser = require("body-parser");
var server = app.listen(3000, function() {
console.log('listening to requests on port 3000');
});
var io = socket(server);
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static('public'));
// Room Logic
var userQueue = [];
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);
});
});
Chat.js (client side):
// Make connection
var socket = io.connect('http://localhost:3000');
// Query DOM
var message = document.getElementById('message');
handle = document.getElementById('handle'),
btn = document.getElementById('send'),
btnNew = document.getElementById('new'),
output = document.getElementById('output'),
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>'
});
// Emit 'is typing'
socket.on('typing', function(data) {
feedback.innerHTML = '<p><em>' + data + ' is typing a message...</em></p>'
});
Index.html:
<!DOCTYPE html>
<html>
<head>
<title>WebSockets 101</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<link rel="stylesheet" type="text/css" href="/styles.css">
</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="Handle">
<input id="message" type="text" placeholder="Message">
<button id="send">Send</button>
<button id="new">New</button>
</div>
<script type="text/javascript" src="/chat.js"></script>
</body>
</html>
I believe that a post request will probably work as well, but if you want to simply work with socket.io you can consider doing something similar to your chat event by adding this in your chat.js:
btnNew.addEventListener('click', function() {
socket.emit('new user', socket.id);
});
And on the server side, app.js:
socket.on('new user', function(id) {
userQueue.push(id);
});
And it should be stored in the array. Hope this helps!
I am creating a chat where there will be a div that displays the users that have connected to the server. The user's name is being taken from a prompt. I have managed to push each connected user to the array but can't figure out how to display that array. At the moment it only appends the div with the name of the individual user but I want them all to be displayed.
<body>
<div id="chatlog" class="col-sm-9">
<ul id="messages"></ul>
</div>
<div id="online" class="col-sm-3">
<div id="username"></div>
</div>
<form class="col-sm-12" action="">
<input id="type" type="text" />
<input type="submit" id="submit" />
</form>
<script>
var socket = io();
var user = prompt("What's your name?");
$('form').submit(function() {
socket.emit('chat message', $('#type').val());
$('#type').val('');
return false;
});
socket.on('chat message', function(msg) {
$('#messages').append($('<li>').text(msg));
});
socket.emit("join", user);
socket.on("join", function(user) {
$("#username").append($("<p>").text(user));
})
</script>
</body>
server.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var express = require("express");
var port = 3000;
var onlineUsers = [];
console.log(onlineUsers);
app.use(express.static(__dirname + '/'));
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket) {
console.log('a user connected');
socket.on("join", function(user) {
socket.emit("join", user);
onlineUsers.push(user);
console.log(onlineUsers);
});
socket.on('chat message', function(msg) {
console.log('message: ' + msg);
io.emit('chat message', msg);
});
socket.on('disconnect', function() {
console.log('user disconnected');
});
});
http.listen(port, function() {
console.log('listening on *:' + port);
});
I am also open to suggestions how to do this another way but node.js is very new to me and think this might be the easiest way.
Send the array of users back to the clients when a user joins. This way all clients will have a updated user list every time a user joins. Below is a suggestion on how you could implement this
server:
socket.on("join", function(user) {
onlineUsers.push(user);
io.emit("user list", onlineUsers);
});
client:
socket.emit("join", user);
socket.on('user list', function(onlineUsers) {
$("#username").empty();
for(var i=0;i<onlineUsers.length;i++){
$("#username").append($("<p>").text(onlineUsers[i]));
}
});
I am just trying to do a very basic chat application with socket.io and node. I am unable to see anything get printed out to my screen, and cannot find any errors. Appreciate the help!
Thanks.
app.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
server.listen(3000);
console.log('Server running...');
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);
});
});
index.html
<html>
<title>Chat Test</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 ="https://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>
</body>
</head>
</html>
When using jQuery, you must spell it jQuery, not JQuery or you could just use the built-in alias $.
This should have shown an error in the debug console of the browser which is something you should learn to look for to see your own errors.
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/>");
});
});
After fixing this and then running your code and accessing http://localhost:3000, your app works just fine for me. Anything submitted in the form is broadcast to all connected clients.
I am trying to make simple chat app using socket.io. Manually it's working fine (via browser localhost:3000/) but I want to write unit tests to verify logic of the server. I don't know which tools/libraries to use for testing.
Here is my node server code:
index.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var socketCount = 0;
http.listen(3000, function(){
console.log('listening on *:3000');
});
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket) {
socketCount++;
console.log('new user connected');
// Let all sockets know how many are connected
io.emit('users connected', socketCount);
socket.on('disconnect', function(){
// Decrease the socket count on a disconnect, emit
socketCount--;
io.emit('users connected', socketCount);
});
socket.on('chat message', function(msg){
// New message added, broadcast it to all sockets
io.emit('chat message', msg);
});
});
And here is my html page:
file: index.html
<html>
...
<body>
<ul id="messages"></ul>
<div class='footer'>
<div id="usersConnected"></div>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</div>
</body>
...
<script>
$(document).ready(function(){
$('#messages').val('');
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
// New message emitted, add it to our list of current messages
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
// New socket connected, display new count on page
socket.on('users connected', function(count){
$('#usersConnected').html('Users connected: ' + count);
});
});
</script>
</html>
Thanks.
I had this problem: How to do unit test with a "socket.io-client" if you don't know how long the server take to respond?.
I've solved so using mocha and chai:
var os = require('os');
var should = require("chai").should();
var socketio_client = require('socket.io-client');
var end_point = 'http://' + os.hostname() + ':8081';
var opts = {forceNew: true};
describe("async test with socket.io", function () {
this.timeout(10000);
it('Response should be an object', function (done) {
setTimeout(function () {
var socket_client = socketio_client(end_point, opts);
socket_client.emit('event', 'ABCDEF');
socket_client.on('event response', function (data) {
data.should.be.an('object');
socket_client.disconnect();
done();
});
socket_client.on('event response error', function (data) {
console.error(data);
socket_client.disconnect();
done();
});
}, 4000);
});
});
I am trying to display any change feed from my rethinkdb database to the HTML (front-end) but I am not able to display any change feed.
Can you please help me how to solve this issue?
The file is app.js
var express = require('express'),
app = express(),
server = require('http').createServer(app),
users = {},
db='testing',
table = 'todos';
io = require('socket.io').listen(server);
var bodyParser = require('body-parser');
server.listen(5000);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
var config = require(__dirname + '/config.js');
var r = require('rethinkdbdash')(config.rethinkdb);
io.sockets.on('connection', function(socket){
r.db(db).table(table).pluck('title').changes().run().
then(function(feed){
feed.each(function(err, item){
console.log(JSON.stringify(item, null, 2));
io.emit('new message', item);
});
});
});
the config.js file
module.exports = {
rethinkdb: {
host: '192.168.2.3',
port: 28015,
authKey: '',
db: 'testing'
},
express: {
port: 5000
}
};
the index.html file
<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>
</body>
</html>
you have some syntax error on index.html which prevents client side running, then the main issue is you pluck on wrong field.
Here is the code that works:
app.js
var express = require('express'),
app = express(),
server = require('http').createServer(app),
users = {},
db='testing',
table = 'todos';
io = require('socket.io').listen(server);
var bodyParser = require('body-parser');
server.listen(5000);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
var config = require(__dirname + '/config.js');
var r = require('rethinkdbdash')(config.rethinkdb);
io.sockets.on('connection', function(socket){
r.db(db).table(table)
.pluck('title')
.changes()
.run()
.then(function(feed){
feed.each(function(err, item){
console.log(JSON.stringify(item, null, 2));
io.emit('new message', item.new_val.title);
})
})
})
index.html
<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>
</body>
</html>
Notice that, on a change feed, you get back documents like this:
{
"new_val": {
"id": "862e6410-f686-4a70-8a52-d4387181d4f2",
"title": "12"
},
"old_val": null
}
If you return the whole document, then the string concat on client $chat.append(data + "<br/>") may get an error or a string of 'object Object' because data is a object, not a string.
If you returns only title like this:
io.emit('new message', item.new_val.title);
Then the string concat will run ok.
Also, your code is very messy. I suggest you get some basic foundation of JavaScript in generally.