I have this simple chat room here:
app.js
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const fs = require('fs');
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket) {
var messages;
fs.readFile('log.txt', 'utf8', function(err, data) {
messages = data.split('|/');
for (i = 0; i < messages.length; i++) {
socket.emit('message', messages[i]);
}
if (err) throw err;
})
socket.on('message', function(data) {
fs.appendFile('log.txt',
'<span class="seen">' + data.name + ': ' + data.msg + '</span>' + '|/',
function(err) {
if (err) throw err;
})
socket.broadcast.emit('message', data);
})
})
http.listen(2099, function(){
console.log('litening on :2099');
});
index.HTML
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<title>chat</title>
<style>
body {
font-family: sans-serif;
font-size: 18px;
background: #404040;
}
input[type=text],[type=submit] {
font-size: 18px;
}
#chatList {
list-style: none;
margin: 0;
padding: 0;
}
#inputContainer {
position: fixed;
bottom: 0;
width: 100%;
margin: 10px;
}
#input {
width: calc(90% - 40px);
padding: 10px 20px;
border: 1px solid white;
border-radius: 10px;
margin-right: -3px;
display: inline-block;
color: white;
background: #404040;
}
#submit {
border: 1px white solid;
border-radius: 10px;
padding: 11px 2.2%;
color: white;
background-color: #404040;
}
.msg {
margin: 0 12px 0px 12px;
padding: 12px;
border-bottom: 1px solid gray;
color: white;
}
.income {
color: crimson;
}
.sender {
color: cyan;
}
</style>
</head>
</head>
<body>
<div id='chat'>
<ul id='chatList'>
</ul>
</div>
<div id='inputContainer'>
<input type="text" id='input' placeholder="Type a message..." autocomplete="off">
<input type="submit" id='submit' value="Send" onclick="send()">
</div>
</form>
<script src='/socket.io/socket.io.js'></script>
<script>
document.getElementById('input').value = '';
var socket = io();
document.addEventListener("keydown", function(e) {
if (e.keyCode == 13) {
send();
}
})
function send() {
value = document.getElementById('input').value;
if (value != '') {
socket.emit('message', {msg: value, name: username})
var list = document.getElementById('chatList');
var msg = document.createElement('li');
msg.className = 'msg';
msg.innerHTML = '<span class="sender">' + username + '</span>' + ': ' + value;
list.appendChild(msg);
document.getElementById('input').value = '';
}
}
socket.on('message', function(data) {
var list = document.getElementById('chatList');
var msg = document.createElement('li');
msg.className = 'msg';
msg.innerHTML = data;
list.appendChild(msg);
})
document.getElementById('input').value = '';
var username = prompt('Choose a username:');
if (username == '') {
username = 'mysteryman' + Math.floor(Math.random() * 100);
}
</script>
</body>
</html>
So this function:
fs.readFile('log.txt', 'utf8', function(err, data) {
messages = data.split('|/');
for (i = 0; i < messages.length; i++) {
socket.emit('messages', messages[i]);
}
if (err) throw err;
})
Were suppose to read data from log.txt and send it as events for the clients to load in old messages. Its working okay but the client side is not receiving any events even though this loop is running and sending events.
I have tried making sure that all events are loaded before sending the data.
Any help would be greatly appreciated!!!
Your typo mistake, you emit messages event on server side, but listen to message (without s) event on client side.
My guess is when the server fires the socket.emit('message'..., the socket in the client has not been registered yet the socket.on('message'...
Related
My teacher told us that we can save the names of users (asking the user to write his nickname in a prompt) using "localstorage" and array, because he wants that the names are saved even if the page is reloaded (sorry for my broken english, english is not my first language and i am also new in javascript) :
html:
<!doctype html>
<html>
<head>
<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="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function() {
var socket=io();
var nick = prompt("Cual es tu nombre");
socket.emit('nombre', nick);
$("form").submit(function(e){
e.preventDefault();
socket.emit('chat message', $("#m").val());
$("#m").val('');
return false;
});
socket.on('chat message',function(msg){
$("#messages").append($("<li>").text(msg));
});
});
Js:
</script>
</body>
</html>
var app=require('express')();
var http=require('http').Server(app);
var io=require("socket.io")(http);
var puerto=8000;
app.get('/',function(req,res){
res.sendFile(__dirname+'/index.html');
});
io.on('connection',function(socket){
socket.on('nombre', (username) => {
socket.username = username;
console.log('Usuario' + socket.username + 'se conecto')
});
//usamos un callback para notificar que una conexion
console.log('usuario conectado'+socket.username);
socket.on('disconnect',function(){
console.log("Usuario se desconecto");
});
socket.on('chat message',function(msg){
console.log(socket.username + " dijo: ", msg);
io.emit('chat message',socket.username + " dijo: "+msg);
});
});
http.listen(puerto,function(){
console.log("Escuchando puerto " +puerto);
});
You can use localStorage to save user nickname and use this data to check user nickname has already or not.
$(function () {
var NICK_NAME_KEY = 'nickName';
var socket = io();
var nick = localStorage.getItem(NICK_NAME_KEY); // first of all, try to get last nickname from localStorage
if (!nick) { // if do not have nickname in localStorage,
// this mean this is the first time user enters your system
nick = prompt("Cual es tu nombre"); // ask user nickname
localStorage.setItem(NICK_NAME_KEY, nick); // save user nickname to localStorage,
//if user reload page, we will have nickname in localStorage, the system will not ask their nickname again.
} else {
// nickname has already
}
socket.emit('nombre', nick);
$("form").submit(function (e) {
e.preventDefault();
socket.emit('chat message', $("#m").val());
$("#m").val('');
return false;
});
socket.on('chat message', function (msg) {
$("#messages").append($("<li>").text(msg));
});
// create a logout `button`, when user click the button, just remove their data (nicknam) and reload page
$('#logout').on('click', function() {
localStorage.removeItem(NICK_NAME_KEY);
location.reload();
})
});
You can literally do this
localStorage.set('userName', NAME_HERE);
so in your case
socket.on('nombre', (username) => {
socket.username = username;
localStorage.set('Usuario', socket.username);
});
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have been trying to make a chat in a long time, but I had no succes in making it.
I tried alot of ways, but making it insert the msg to my database and then with javascript refresh the chat every second, and get the msg from database, but that dosent work that well.
I was wondering is theire a way to make a chat with only javascript?
So it appends to a div all the users can see.
I saw some sites do this but I haven't been able to do it myself.
Yes - You can make a chat client that takes advantage of Websockets.
The only thing required is that you run a server in order to forward requests to other clients as they arrive.
The server can be written in a variety of different languages -- some of the most popular are C/C++ (Qt), node.js, Python, and go.
There are more languages which can provide this as ability as well ---
This came from http://www.tutorials.kode-blog.com/websocket-chat-client
var output;
var websocket;
function WebSocketSupport() {
if (browserSupportsWebSockets() === false) {
document.getElementById("ws_support").innerHTML = "<h2>Sorry! Your web browser does not supports web sockets</h2>";
var element = document.getElementById("wrapper");
element.parentNode.removeChild(element);
return;
}
output = document.getElementById("chatbox");
websocket = new WebSocket('ws:localhost:999');
websocket.onopen = function(e) {
writeToScreen("You have have successfully connected to the server");
};
websocket.onmessage = function(e) {
onMessage(e)
};
websocket.onerror = function(e) {
onError(e)
};
}
function onMessage(e) {
writeToScreen('<span style="color: blue;"> ' + e.data + '</span>');
}
function onError(e) {
writeToScreen('<span style="color: red;">ERROR:</span> ' + e.data);
}
function doSend(message) {
var validationMsg = userInputSupplied();
if (validationMsg !== '') {
alert(validationMsg);
return;
}
var chatname = document.getElementById('chatname').value;
document.getElementById('msg').value = "";
document.getElementById('msg').focus();
var msg = '#<b>' + chatname + '</b>: ' + message;
websocket.send(msg);
writeToScreen(msg);
}
function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
function userInputSupplied() {
var chatname = document.getElementById('chatname').value;
var msg = document.getElementById('msg').value;
if (chatname === '') {
return 'Please enter your username';
} else if (msg === '') {
return 'Please the message to send';
} else {
return '';
}
}
function browserSupportsWebSockets() {
if ("WebSocket" in window) {
return true;
} else {
return false;
}
}
body {
font: 12px arial;
color: #222;
text-align: center;
padding: 35px;
}
#controls,
p,
span {
margin: 0;
padding: 0;
}
input {
font: 12px arial;
}
a {
color: #0000FF;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
#wrapper,
#loginform {
margin: 0 auto;
padding-bottom: 25px;
background: #66CCFF;
width: 504px;
border: 1px solid #ACD8F0;
}
#chatbox {
text-align: left;
margin: 0 auto;
margin-bottom: 25px;
padding: 10px;
background: #fff;
height: 270px;
width: 430px;
border: 1px solid #ACD8F0;
overflow: auto;
}
#chatname {
width: 395px;
border: 1px solid #ACD8F0;
margin-left: 25px;
float: left;
}
#msg {
width: 395px;
border: 1px solid #ACD8F0;
}
#submit {
width: 60px;
}
<!DOCTYPE html>
<html>
<head>
<title>WebSocket PHP Open Group Chat App</title>
<link type="text/css" rel="stylesheet" href="style.css" />
<script src="websocket_client.js"></script>
</head>
<body onload="javascript:WebSocketSupport()">
<div id="ws_support"></div>
<div id="wrapper">
<div id="menu">
<h3 class="welcome">Welcome to WebSocket PHP Open Group Chat App v1</h3>
</div>
<div id="chatbox"></div>
<div id="controls">
<label for="name"><b>Name</b>
</label>
<input name="chatname" type="text" id="chatname" size="67" placeholder="Type your name here" />
<input name="msg" type="text" id="msg" size="63" placeholder="Type your message here" />
<input name="sendmsg" type="submit" id="sendmsg" value="Send" onclick="doSend(document.getElementById('msg').value)" />
</div>
</div>
</body>
</html>
Hello I am very new to Meteor and am trying to learn and get acquainted with the Meteor platform.
So I am working on building a Meteor app {https://github.com/ahadsheriff/SheriffMessenger}
which is based off another example I saw {http://chatt.meteor.com/ (note: the original app was built using an older version of meteor and some of the packages were not necessary in the current version (mine)) The purpose of me cloning the example app is to experiment with meteor and the app itself, the idea is (once I get it to work) break the code down and study each individual element to understand how meteor works.
In my clone everything looks fine except two of the main features are not working in my version: the chat/messaging functionality and the ability to see which user(s) you are communicating with and to see whether they are online.
I have installed all the packages that I possibly could (packages that were supported in the latest build of Meteor), and I think my problem might be with the lack of some fundamental packages.
Anyways I was wondering if somebody could help me sift through the code and see where my problem is, so I can get the app to work and get back to breaking this code down!
Any help is appreciated!
I have posted the github link above and I will post the HTML and Javascript code below for your convenience.
Thank you, your help will be very much appreciated!!!
HTML:
<template name="layout">
<head>
<title>Simple chat</title>
<link href='http://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'>
</head>
<!-- Wrap all page content here -->
{{> yield}}
</template>
<template name="channel">
<div class="container">
<div class="row">
<div class="col-md-3">
{{> presentation}}
</div>
<div class="col-md-6">
{{> chat}}
</div>
<div class="col-md-3">
{{> participants}}
</div>
</div>
</div>
</template>
<template name="homepage">
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="header">
<h1>Sheriff Messenger</h1>
<h2>Chat. Like a Sheriff.</h2>
</div>
<div class="landing">
<form class="form-inline" role="form">
<div class="form-group">
<input type="text" class="form-control" id="channelInput" placeholder="username" maxlength="20" />
<button type="button" id="channelButton" class="btn btn-default">enter</button>
</div>
</form>
<div class="channels">
<ul class="pager">
{{#each channels}}
<li>{{ name }} - {{ participants.length }} <span class="glyphicon glyphicon-user"></span></li>
{{/each}}
</ul>
</div>
</div>
</div>
</div>
</div>
</template>
<template name="presentation">
<h1>Sheriff Messenger</h1>
</template>
<template name="participants">
<h3>Participants</h3>
<ul>
{{#each participants}}
<li style="list-style-type: none;"><div class="color-swatch" style="background-color:{{labelClass}};"></div> {{ profile.name }}</li>
{{/each}}
</ul>
<p>Edit your name : </p>
<input type="text" class="form-control" id="nameInput" placeholder="{{name}}" maxlength="40" />
</template>
<template name="chat">
<div class="chat">
<div class="conversation commentArea" id="scroll">
{{#each messages }}
{{#if message}}
<div class="{{authorCss author}}">
{{breaklines message }}<br/>
<i class="author">{{ name }}</i>
</div>
{{else}}
<div class="bubbledLeft">
<i class="author">Sheriff Messenger</i>
</div>
{{/if}}
<script> if (typeof(scrolldown) == "function") { scrolldown(); }</script>
{{/each}}
</div>
<div class="conversationInput">
<input type="text" id="messageInput" class="form-control text" placeholder="Message..." maxlength="300">
</div>
</div>
<script type="text/javascript">
/* Call it everytime ? ....
around 10 times at the first call...
*/
var scrolldown = function() {
console.log("one scrolldown call..."); // reminder to debug...
var elem = document.getElementById('scroll');
elem.scrollTop = elem.scrollHeight;
}
</script>
</template>
Javascript:
var MeteorUser = function () {
var userId = Meteor.userId();
if (!userId) {
return null;
}
var user = Meteor.users.findOne(userId);
/* if (user !== undefined &&
user.profile !== undefined &&
user.profile.guest) {
return null;
} */
return user;
};
////////// Helpers for in-place editing //////////
// Returns an event map that handles the "escape" and "return" keys and
// "blur" events on a text input (given by selector) and interprets them
// as "ok" or "cancel".
var okCancelEvents = function (selector, callbacks) {
var ok = callbacks.ok || function () {};
var cancel = callbacks.cancel || function () {};
var events = {};
events['keyup '+selector+', keydown '+selector+', focusout '+selector] =
function (evt) {
if (evt.type === "keydown" && evt.which === 27) {
// escape = cancel
cancel.call(this, evt);
} else if (evt.type === "keyup" && evt.which === 13 ||
evt.type === "focusout") {
// blur/return/enter = ok/submit if non-empty
var value = String(evt.target.value || "");
if (value)
ok.call(this, value, evt);
else
cancel.call(this, evt);
}
};
return events;
};
var activateInput = function (input) {
input.focus();
input.select();
};
UI.registerHelper('breaklines', function(text){ // Should call a fonction to sanitaze the html...
var html = "";
if(text) {
html = text.replace(/(\r\n|\n|\r)/gm, '<br>');
}
return Spacebars.SafeString(html);
});
// Not the right way to do it ?!!!
UI.registerHelper('authorCss', function(author){
var cssClass = "bubbledLeft";
if(author === Meteor.userId()) {
cssClass = "bubbledRight";
}
return cssClass;
});
/////////// End Helper ///////
if (Meteor.isClient) {
// Create collection on client
Messages = new Meteor.Collection('messages');
Channels = new Meteor.Collection('channels');
Meteor.startup(function() {
Meteor.loginVisitor(); // Guest Account
//Meteor.insecureUserLogin('Anonymous'); // Test Account
// We take car of the name
Session.setDefault('name', 'Guest');
Session.setDefault('channel', 'yo');
});
//////////// Chat ///////////////
Template.chat.messages = function () {
var messagesCursor = Messages.find({}, {sort:{timestamp:-1}, limit:42});
var messages = messagesCursor.fetch().reverse(); // Should use observechnage to avoid over computation ?
for (var i = messages.length - 1; i >= 0; i--) {
var user = Meteor.users.findOne(messages[i].author);
if (user) {
messages[i].name = user.profile.name;
}
else {
messages[i].name = "Unknown";
}
};
var conversations = [];
var newConversation = messages[0];
for (var i = 0; i <= messages.length - 2; i++) {
var timedelta = messages[i+1].timestamp - messages[i].timestamp;
var sameauthor = (messages[i+1].author === messages[i].author);
if (timedelta <= 30000 && sameauthor) {
newConversation.message = newConversation.message + " \n" + messages[i+1].message;
}
else {
conversations.push(newConversation);
newConversation = messages[i+1];
}
};
conversations.push(newConversation);
// title bar alert
$.titleAlert("New chat message!", {requireBlur: true});
return conversations;
};
Template.chat.events(okCancelEvents(
'#messageInput',
{
ok: function (value, evt) {
Messages.insert({
author: Meteor.userId(),
message: value,
timestamp: (new Date()).getTime(),
channel: Session.get('channel')
});
evt.target.value = "";
}
}
));
//////////// End Chat ///////////////
//////////// Name ///////////////
Template.participants.name = function () {
Meteor.users.findOne(userId)
var user = Meteor.users.findOne(Meteor.userId());
if (user){
Session.set('name', user.profile.name);
}
return Session.get('name');
};
Template.participants.participants = function() {
var labelClass = function(id) { // Certainly not the right way to do it...
if (id === Meteor.userId()) {
return "#428bca";
}
var user = Meteor.users.findOne(id);
if (user) {
if (user.status.online) {
return "#5cb85c";
}
else {
return "#f0ad4e";
}
}
else {
return '#d9534f';
}
};
var participants = Meteor.users.find({}).fetch();
for (var i = participants.length - 1; i >= 0; i--) {
participants[i].labelClass = labelClass(participants[i]._id);
};
return participants;
}
Template.participants.events(okCancelEvents(
'#nameInput',
{
ok: function (value, evt) {
if (value) {
var user = Meteor.users.findOne(Meteor.userId());
if (user){
Meteor.users.update({_id:Meteor.userId()}, {$set:{"profile.name": value}})
}
Session.set('name', value);
}
}
}));
//////////// End Name ///////////////
//////////// Homepage ///////////////
Template.homepage.events(okCancelEvents(
'#channelInput',
{
ok: function (value, evt) {
if (value) {
Session.set('channel', value);
}
}
}));
Template.homepage.channel = function () {
return Session.get('channel');
};
Template.homepage.channels = function() {
return Channels.find({}, {limit:42});
}
Template.homepage.events({
'click #channelButton': function (event, template) {
Router.go('/c/'+Session.get('channel'));
}
});
//////////// END Homepage ///////////
//////////// Routing ///////////////
Router.configure({
layoutTemplate: 'layout'
});
Router.map(function () {
this.route('channel', {
path: '/c/:channel',
template: 'channel',
layoutTemplate: 'layout',
waitOn: function () {
Session.set('channel', this.params.channel);
// Subscribe
Meteor.subscribe("chatroomMessages", this.params.channel);
Meteor.subscribe("channels", this.params.channel);
},
data: function() {
var channel = Channels.findOne({name: this.params.channel});
var participants = [Meteor.userId()]; // default;
if (channel) {
var participants = channel.participants;
}
Meteor.subscribe("users", participants);
}
});
this.route('home', {
path: '/',
template: 'homepage',
layoutTemplate: 'layout',
data: function() {
Meteor.subscribe("channelslist");
}
});
});
//////////// END Routing ///////////
}
if (Meteor.isServer) {
Meteor.startup(function () {
Messages = new Meteor.Collection('messages');
Channels = new Meteor.Collection('channels');
// code to run on server at startup
});
Meteor.publish("channelslist", function() {
return Channels.find({});
});
Meteor.publish("channels", function (channel) {
var id;
if (Channels.findOne({name:channel}) == null) {
id = Channels.insert({
name : channel,
created_timestamp : (new Date()).getTime(),
created_author: this.userId,
participants: [],
message : 0
});
} else {
id = Channels.findOne({name:channel})._id;
}
if (id) {
Channels.update({_id: id}, {$addToSet: { participants: this.userId}});
}
return Channels.find({});
});
Meteor.publish("users", function (listUsers) {
return Meteor.users.find({_id: {$in: listUsers}});
});
Meteor.publish("chatroomMessages", function (channel) {
return Messages.find({channel: channel}, {sort:{timestamp:-1}, limit:42});
});
}
And just in case...here is the CSS:
/* CSS declarations go here */
#media (min-width: 1200px) {
[class*="span"] {
margin-left: 20px; /* correction ??? */
}
}
body {
background-color: #e7e7e7;
}
.chat {
height: 100vh; /* What is that ? */
background-color: #fff;
-webkit-box-shadow: 0px 3px 5px 0px rgba(0, 0, 0, 0.61);
-moz-box-shadow: 0px 3px 5px 0px rgba(0, 0, 0, 0.61);
box-shadow: 0px 3px 5px 0px rgba(0, 0, 0, 0.61);
}
.conversation {
height: calc(100% - 50px); /* Use preprocessing to get a fixed .conversationInput-height */
overflow-x:hidden;
overflow-y: auto;
}
.conversationInput {
background-color: #ccf;
height: 50px;
bottom: 0;
}
/* CSS chat 'stolen' from http://jsfiddle.net/anuradhabajpai/x8C8S/10/ */
.commentArea {
font: 14px Arial;
padding: 0 10px 0px;
}
.bubbledLeft,.bubbledRight {
margin-top: 10px;
margin-bottom: 10px;
padding: 5px 9px;
max-width: 80%;
clear: both;
position: relative;
}
.bubbledLeft{
float: left;
margin-right: auto;
-webkit-border-radius: 8px 8px 8px 0px;
-moz-border-radius: 8px 8px 8px 0px;
-o-border-radius: 8px 8px 8px 0px;
-ms-border-radius: 8px 8px 8px 0px;
border-radius: 8px 8px 8px 0px;
background-color: #65B045;
color: #ffffff;
}
.bubbledLeft:before {
border-bottom: 10px solid #65B045;
border-left: 9px solid rgba(0, 0, 0, 0);
position: absolute;
bottom: 0;
left: -8px;
content: "";
}
.bubbledRight{
float: right;
margin-left: auto;
text-align: right;
-webkit-border-radius: 8px 8px 0px 8px;
-moz-border-radius: 8px 8px 0px 8px;
-o-border-radius: 8px 8px 0px 8px;
-ms-border-radius: 8px 8px 0px 8px;
border-radius: 8px 8px 0px 8px;
background-color: #07D;
color: white;
}
.bubbledRight:before {
border-bottom: 9px solid #07D;
border-right: 9px solid rgba(0, 0, 0, 0);
position: absolute;
bottom: 0;
right: -8px;
content: "";
}
.author {
opacity: .5;
font-size: .9em;
}
/* END CSS Chat */
#messageInput {
width: 100%;
padding: 0px;
padding-left: 16px;
height: 100%;
border-bottom: 0;
border-radius: 0;
}
.color-swatch {
width: 12px;
height: 12px;
display: inline-block;
border-radius: 50%;
}
body {
font-family: 'Roboto', sans-serif;
}
.landing {
padding-top: 150px;
text-align: center;
}
.channels {
padding: 10px 10px 10px 10px;
}
h1 {
text-decoration: none;
text-decoration-color: none;
color: #333;
}
.header h1 {
text-align: center;
}
Also here is a list of the packages I used:
meteor-platform
autopublish
insecure
mrt:moment
ostrio:user-status
accounts-base
accounts-password
artwells:accounts-guest
mizzao:accounts-testing
fortawesome:fontawesome
iron:router
twbs:bootstrap
meteorhacks:fast-render
peerlibrary:related
standard-app-packages
Once again thank you for the help!
Might not at all be the only reason, but in var participants = Meteor.users.find({}).fetch(); the fetch() shouldn't be there...
The same goes for those lines:
var messagesCursor = Messages.find({}, {sort:{timestamp:-1}, limit:42});
var messages = messagesCursor.fetch().reverse();
I am new to meteor and mongodb too, but there is only two fetch() in your code, and both where you have problems... And since I haven't seen that on mongdb, I find it highly probable that it is your problem.
Edit:
Also, you use Meteor.users.findOne(id) which should be Meteor.users.findOne({_id:id}). Same for Meteor.users.findOne(messages[i].author);
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
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>