I'm trying to create a chat system, where a user can send message to everybody (and this message is displayed in the div with id "chat") and I've achieved this feature. Now I'd like to implement a private chat. A user can click on another user's name on the right column (which shows all logged users), once he clicked on a username a little window will appear (div with class "chatpopup") and in this window there is a submit button and an input text to be filled with a message, once submit button has been clicked the message should be sent to the other user.
This is what I have, if I click on a user (on the right side of the screen) the little window (chatpopup) is shown but when I try to submit the form inside this little window the app crashes.
I'd also like to receive some hints about building a private chat, for example how can I open a new window (with the message receive) in the client side of the user that should receive the message?
index.html
<html>
<head>
<title>Chat with socket.io and node.js</title>
<style>
#contentWrap
{
width:100%;
display: none;
}
#chatWrap {float: left; width:80%;}
#chat
{
height:500px;
width:96%;
border: 1px #000 solid;
padding-left:2%;
padding-right:2%;
}
#users
{
margin-left:82%; width:15%;
height:500px;
border: 1px #000 solid;
text-align:right;
}
#send-message {margin-top:3%; width:100%;}
#message {width:80%;}
.err1r{ padding-top:1%;
color: red;
}
.whisper{
color: gray;
font-style: italic;
}
p.sideusername:nth-child(even) {background-color:#FAFAFA; padding-bottom:5%; padding-top:5%;}
p.sideusername:nth-child(odd) {background-color: #f5f5f0; padding-bottom:5%; padding-top:5%;}
.chatpopup {width:350px; height: 250px; background-color:blue;}
#interlocutore {background-color:red; height: 30px; text-align: left;}
#msgspace {height:150px; background-color:yellow;}
</style>
</head>
<body>
<div id="nickWrap">
<p>Enter a username:</p>
<p id="nickError"></p>
<form id="setNick">
<input size="35" id="nickname"></input>
<input type="submit"></input>
</form>
</div>
<div id="contentWrap">
<div id="chatWrap">
<div id="chat"></div>
<form id="send-message">
<input size="35" id="message"></input>
<input type="submit"></input>
</form>
</div>
<div id="users"></div>
</div>
<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 $nickForm = $('#setNick');
var $nickError = $('#nickError');
var $nickBox = $('#nickname');
var $users = $('#users');
var $messageForm = $('#send-message');
var $messageFormPopup = $('#send-message-popup');
var $messageBox = $('#message');
var $messageBoxPopup = $('#messagePopup');
var $chat = $('#chat');
$nickForm.submit(function(e){
e.preventDefault();
socket.emit('new user', $nickBox.val(), function(data){
if(data){
$('#nickWrap').hide();
$('#contentWrap').show();
} else{
$nickError.html('That username is already taken! Try again.');
}
});
$nickBox.val('');
});
socket.on('usernames', function(data){
$users.empty();
for(var i=0; i < data.length; i++){
$users.append('<p class="sideusername">' + data[i] + "</p>");
}
});
$messageForm.submit(function(e)
{
e.preventDefault();
socket.emit('send message', $messageBox.val(), function(data)
{
});
$chat.append('<span class="error">' + data + "</span><br/>");
$messageBox.val('');
});
$messageFormPopup.submit(function(e)
{
e.preventDefault();
socket.emit('send popup message', $messageBoxPopup.val(), function(dataPopup)
{
});
$messageBoxPopup.val('');
});
socket.on('load old msgs', function(docs){
for(var i=docs.length-1; i >= 0; i--){
displayMsg(docs[i]);
}
});
socket.on('new message', function(data){
displayMsg(data);
});
function displayMsg(data){
$chat.append('<span class="msg"><b>' + data.nick + ': </b>' + data.msg + "</span><br/>");
}
socket.on('whisper', function(data){
$chat.append('<span class="whisper"><b>' + data.nick + ': </b>' + data.msg + "</span><br/>");
});
$(document).on("click", ".closepopup", function() {
$(this).parents('.chatpopup').hide();
});
$(document).on("click", ".sideusername", function()
{
var interlocutore = $(this).text();
$chat.append('<div class="chatpopup"><table><tr><td id="interlocutore"></td><td><p class="closepopup">X</p></td></tr><tr><td colspan="2" id="msgspace"></td></tr><tr><td colspan="2"><form id="send-message-popup"> <input size="35" id="messagePopup"></input><input type="submit"></input></form></td></tr></table></div>');
$('#interlocutore').append(interlocutore);
});
});
</script>
</body>
</html>
app.js
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
mongoose = require('mongoose'),
users = {};
server.listen(3000);
mongoose.connect('mongodb://localhost/chat', function(err)
{
if(err)
console.log(err);
else console.log('Connected to mongodb!');
});
var chatSchema = mongoose.Schema(
{
nick: String,
msg: String,
created: {type: Date, default: Date.now}
});
var Chat = mongoose.model('Message', chatSchema);
app.get('/', function(req, res)
{
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket)
{
var query = Chat.find({});
query.sort('-created').limit(8).exec(function(err, docs)
{ // carico gli ultimi 8 messaggi in ordine di data
if(err) throw err;
socket.emit('load old msgs', docs);
});
socket.on('new user', function(data, callback)
{
if (data in users)
callback(false);
else
{
callback(true);
socket.nickname = data;
users[socket.nickname] = socket;
updateNicknames();
}
});
function updateNicknames()
{
io.sockets.emit('usernames', Object.keys(users));
}
socket.on('send message', function(data, callback)
{
var msg = data.trim();
var newMsg = new Chat({msg: msg, nick: socket.nickname});
newMsg.save(function(err)
{
if(err) throw err;
io.sockets.emit('new message', {msg: msg, nick: socket.nickname});
});
socket.on('disconnect', function(data)
{
if(!socket.nickname) return;
delete users[socket.nickname];
updateNicknames();
});
});
socket.on('send popup message', function(data, callback)
{
/*var msgPopup = dataPopup.trim();
if (msgPopup !== "")
users[interlocutore].emit('whisper', {msg: msgPopup, nick: socket.nickname});
*/
var msg = data.trim()+" hello";
var newMsg = new Chat({msg: msg, nick: socket.nickname});
newMsg.save(function(err)
{
if(err) throw err;
io.sockets.emit('new message', {msg: msg, nick: socket.nickname});
});
socket.on('disconnect', function(data)
{
if(!socket.nickname) return;
delete users[socket.nickname];
updateNicknames();
});
});
});
To create a private chat using socket.IO, you need to first understand how rooms in socket.IO work. You can find loads of tutorials. You can also see this post for help.
Now you need to extend this functionality to create a private chat system. In order to do so, you need to have an unique id for each client that is either connected or is online. socket.id is an unique key that each client gets upon joining the chat.
On the client side, you can emit a name along with the message to the server. You do so like this:
socket.emit('privateMessage', 'theUserName', message);
On the server side, you could manage an array of the users who are connected and save their unique usernames or id's.
var connectedClients = {};
So each time an user connects to the chat, (for which you are probably using the new user event), save the user's id in the connectedClients.
connectedClients[username] = socket.id;
Where username is the name that is sent to the server while an user is connecting to the chat system. (I hope you know how to do this. If not, do ask me.)
Then we make a listener to listen to the privateMessage event and emit to the message to that particular user, we do:
socket.on('privateMessage', function(to, message) {
var id = connectedClients[to];
io.sockets.socket(id).emit('sendPrivateMessage', socket.username, message);
});
Finally, on the client side, your listener for the sendPrivateMessage receives the message and you can update your view accordingly.
The idea is that the server saves each socket connected to it by the username: users[socket.nickname] = socket;
so whenever a user send a message to another user - you should emit an event - send to that the username of the other user - take the socket of that user and emit him a message:
client:
socket.emit('sendPrivate','someusername','message');
socket.on('privateMsg',function(from,msg){
//write private message from user 'from'
});
server:
socket.on('sendPrivate',function(to,msg){
users[to].emit('privateMsg',socket.username,msg);
});
Related
I've been playing around a bit with NodeJS and recently socket.IO, I come from PHP development and try to understand really how to work with Node and socket.IO
I started building a chat app and when I were to test it on different devices I noticed that when I for instance log in to another account through my phone, the browser window updates and gets the same user as I logged into on my phone
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: 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>
</head>
<body>
<div id="chatLogin">
<input type="text" name="password" id="username" placeholder="Username..." /><br>
<input type="password" name="password" id="password" placeholder="Password..." /><br>
<button id="chatLoginBtn">Login / Register</button>
</div>
<div id="chatWindow">
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</div>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>
$(function () {
var socket = io();
$(document).ready(function(){
$("#chatWindow").hide();
$("#chatLoginBtn").click(function(){
socket.emit('loginForm', {
username: $("#username").val(),
password: $("#password").val()
});
});
});
socket.on('returnValue', function(msg) {
var html = '<ul id="messages"></ul>' +
'<form id="sendMsg" action="">' +
'<input id="m" autocomplete="off" /><button>Send</button>' +
'</form>';
$("#chatLogin").html("").hide();
$("#chatWindow").html(html).show();
$('#sendMsg').submit(function(e) {
e.preventDefault(); // prevents page reloading
var time = Date.now();
var msg = $("#m").val();
var data = [time, msg];
socket.emit('chat', data);
$('#m').val('');
return false;
});
});
socket.on('chat', function(msg){
$('#messages').append($('<li>').text(msg));
});
});
</script>
</body>
</html>
index.js
var app = require('express')();
var http = require('http').createServer(app);
var phpPass = require('node-php-password');
var mysql = require('mysql');
var io = require('socket.io')(http);
var cookieParser = require('cookie-parser');
var session = require('express-session');
// DECLARE the variables we will be using
// These does not change
let userCount = 0;
// These are declared to be later set
var displayName;
var userDataID;
// POOL MySQL Connection
var pool = mysql.createPool({
connectionLimit : 100,
host : 'localhost',
user : 'root',
password : '....',
port : '3306',
database : '....',
debug : false
});
// session & cookieParser
/*var sessionMiddleware = session({
secret: "keyboard cat"
});
io.use(function (socket, next) {
sessionMiddleware(socket.request, socket.request.res, next);
});
app.use(sessionMiddleware);
app.use(cookieParser());*/
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
var hashPassword;
function checkUser(user, Password, userID) {
pool.getConnection(function(error,connection) {
connection.query("SELECT password FROM accounts WHERE `username` = '"+user+"' LIMIT 1",function(error,rows){
if (!error) {
var hashPassword = rows[0].password;
if (phpPass.verify(Password, hashPassword)) {
console.log(Password);
console.log(hashPassword);
console.log("Went well");
// UPDATE user database with current socketID
connection.query("UPDATE accounts SET `socketID` = '"+userID+"' WHERE `username` = '"+user+"'",function(error,result){
connection.release();
if (!error) {
connection.query("SELECT id,displayName,username,email,fullName,dateofBirth,created,lastSignedIn FROM accounts WHERE socketID = '"+userID+"' LIMIT 1",function(error,userData){
if (!error) {
displayName = userData[0].displayName;
userDataID = userData[0].id;
console.log("Current user: " + userData[0].displayName);
} else {
console.log("Error" + error);
}
});
console.log("No error" + result);
} else {
console.log("We found error" + error);
}
});
// send to function to gather all needed info from database and save for the current session
return true;
} else {
console.log("Wrong pass");
return false;
}
console.log(hashPassword);
} else {
console.log(error);
return false;
}
});
connection.on('error', function(error) {
});
});
return true;
};
io.on('connection', (socket) => {
var req = socket.request;
var userID = socket.id;
// When connection is inited
userCount++;
console.log('User connected' + userCount);
// Take the data from login and pass to check if it is valid
socket.on("loginForm", function(data){
const user = data.username,
pass = data.password;
//console.log(checkUser(user, pass));
if (checkUser(user, pass, userID)) {
io.emit('returnValue', 'hi');
}
});
function joinRoom(room) {
socket.join(room);
console.log("Joined " + room);
return io.emit('chat', "Joined new room " + room);
}
socket.on('join', (data) => {
socket.join(data);
console.log("Joined " + data);
});
socket.on('chat', (data) => {
/* Array: Data;
[0] Time
[1] Message
[2] socketID
[3] User
*/
var msg = data[1];
var time = data[0];
// Calc time
var date = new Date(time);
var hours = date.getHours();
var minutes = date.getMinutes();
var formatted = hours + ":" + minutes;
if (minutes < 10) return minutes = "0" + minutes;
var dateFormatted = "[" + formatted + "] ";
//data.push(user);
pool.getConnection(function(error,connection) {
connection.query("INSERT INTO `chat_messages` (userID, socketID, message, time) VALUES ('"+userDataID+"', '"+userID+"', '"+msg+"', '"+time+"')",function(error,rows){
connection.release();
if (!error) {
console.log("Success");
} else {
console.log(error);
}
});
});
if (msg.startsWith('/me')) return io.emit('chat', dateFormatted + displayName + msg.substring(3));
if (msg.startsWith('/join')) return joinRoom(msg.substring(6));
if (msg.startsWith('/rooms')) return console.log(io.sockets.adapter.rooms);
return io.emit('chat', dateFormatted + displayName + ' said: ' + msg);
//console.log(displayName + 'said:' + msg);
});
// When user disconnects
socket.on('disconnect', () => {
userCount--;
console.log('User disconnected!' + userCount);
});
});
http.listen(3000, () => {
console.log('Listening on *:3000');
});
I do not get any errors and it counts the number of users correctly
The problem is that the user first logged in gets switched to the last logged in user
How do I make the user session unique and so multiple clients can be logged in into different accounts?
I noticed an issue: var userDataID;
It's a global variable. Each time a new user log ing, the userDataID will be updated. It's always the ID of the newest logged user. Then, all new messages will be stored in the database with the userDataID.
EX:
- Log in by account A on window, the userDataID = 1;
- send some messages to server, these message will be stored with userID = 1
- Log in by account B on iphone, the userDataID will be updated, it's = 2 now.
- send some messages from windown & iphone. all these message will be stored with userID 2.
I think that's the error you got.
Should store userID in cookie or session.
I'm using node.js and I get the error in the picture every single time a client disconnects (This happens when I just close the tab and I've also tried using socket.disconnect() on both the client and the server side)
here's my code
var io = require('socket.io').listen(4000);
var fs = require('fs');
io.sockets.on('connection', function(socket) {
socket.on('login', function(info)
{
fs.readFile("chatLog.txt", function(err, data)
{
if(err)
{
return console.error(err);
}
socket.emit('incomingMessage', data.toString());
});
socket.broadcast.emit('newUser', info);
});
socket.on('message', function(content) {
console.log(content);
io.sockets.emit('incomingMessage', content);
});
socket.on('logout', function(name)
{
socket.broadcast.emit('incomingMessage', "user: " + name + " has logged out");
//socket.disconnect();
});
});
can anyone tell me how to disconnect without having the server crash with that error?
client side HTML:
<html>
<head>
<!-- This is the websocket SERVER -->
<script src="http://localhost:4000/socket.io/socket.io.js"></script>
<script src="client.js"></script>
</head>
<body>
<div id="loginDiv">
username: <input type="text" id = "userName"><br>
<input type = "button" id="login" value = "login" onClick="login()">
</div>
<div id="logoutDiv" style="visibility:hidden">
<input type = "button" id = "messageRedir" value = "send message" onClick= "gotoMessage()">
<input type = "button" id = "logout" value = "logout" onClick="logout()">
</div>
<div id="sendMessage" style="visibility:hidden">
<input type = "text" id="messageBox"><br>
<input type = "button" value="send message" onClick="sendMessage()">
<input type = "button" value = "cancel" onClick="back">
</div>
<div id="msg"></div>
</body>
</html>
Client side JS:
var userName = null;
var socket = null;
function login()
{
socket = io.connect('http://localhost:4000');
userName = document.getElementById('userName').value;
document.getElementById("loginDiv").style.visibility = "hidden";
document.getElementById("logoutDiv").style.visibility = "visible";
socket.emit('login', userName+ ' has connected');
// Attach event handler for event fired by server
socket.on('incomingMessage', function(data) {
var elem = document.getElementById('msg');
console.log(data);
elem.innerHTML = data + "<br>" + elem.innerHTML; // append data that we got back
});
socket.on('newUser', function(data) {
var elem = document.getElementById('msg');
console.log(data);
elem.innerHTML = data + "<br>" + elem.innerHTML; // append data that we got back
});
}
function logout()
{
document.getElementById("loginDiv").style.visibility = "visible";
document.getElementById("logoutDiv").style.visibility = "hidden";
document.getElementById('msg').innerHTML = "";
socket.emit('logout', userName);
socket.disconnect();
socket = null;
}
function gotoMessage()
{
document.getElementById("loginDiv").style.visibility = "hidden";
document.getElementById("msg").style.visibility = "hidden";
document.getElementById("sendMessage").visibility = "visible";
}
function back()
{
document.getElementById("loginDiv").style.visibility = "visible";
document.getElementById("msg").style.visibility = "visible";
document.getElementById("sendMessage").visibility = "hidden";
}
function sendMessage()
{
var mess = document.getElementById('messageBox').value;
socket.emit('message', mess);
}
The problem is most likely in the logout function where you are using the socket (that is no longer active) to emit an event. You should use io.sockets.emit instead. I have some suggestions.
Instead of using the socket.emit('logout', username) event on the client side, use the built in logout event that gets fired when the user close the browser. That event is disconnect. You don't need to pass the username with each request either. You only need to pass it once with the login event. Then you can store the username on the server as a property of the socket.
Client Side
function login()
{
socket = io.connect('http://localhost:4000');
userName = document.getElementById('userName').value;
document.getElementById("loginDiv").style.visibility = "hidden";
document.getElementById("logoutDiv").style.visibility = "visible";
// just send the username
socket.emit('login', userName);
// Attach event handler for event fired by server
socket.on('incomingMessage', function(data) {
var elem = document.getElementById('msg');
console.log(data);
elem.innerHTML = data + "<br>" + elem.innerHTML; // append data that we got back
});
socket.on('newUser', function(data) {
var elem = document.getElementById('msg');
console.log(data);
elem.innerHTML = data + "<br>" + elem.innerHTML; // append data that we got back
});
}
function logout()
{
document.getElementById("loginDiv").style.visibility = "visible";
document.getElementById("logoutDiv").style.visibility = "hidden";
document.getElementById('msg').innerHTML = "";
socket.disconnect();
socket = null;
}
Server Side
io.sockets.on('connection', function(socket) {
socket.on('login', function(uxname)
{
// store username variable as property of the socket connection
// this way we can handle the disconnect message later
this.username = uxname;
fs.readFile("chatLog.txt", function(err, data)
{
if(err)
{
return console.error(err);
}
socket.emit('incomingMessage', data.toString());
});
socket.broadcast.emit('newUser', uxname);
});
socket.on('message', function(content) {
console.log(content);
io.sockets.emit('incomingMessage', content);
});
socket.on('disconnect', function(){
// don't use socket.broadcast.emit. at this point the socket is destroyed and you cant call events on it. That is most likely why you have the error.
// use io.sockets.emit instead
io.sockets.emit('incomingMessage', "user: " + this.username + " has logged out")
});
});
I'm trying to emit messsage to specific rooms, once the "joinedRoom' listener is triggered by the client, the code works fine if I place my code outside the joinedRoom listeners, otherwise it does nothing.
Code:
app.get('/room/:room/user/:user', function(req, res){
var room = {
username: req.params.user,
roomname: req.params.room
};
res.render('room', room);
});
var users = {};
io.sockets.on('connection', function (socket) {
socket.on('joinedRoom', function(roomData){
socket.username = roomData.username;
socket.room = roomData.roomname;
console.log("Roomname: " + socket.room);
console.log("Username: " + socket.username);
socket.join(socket.room);
socket.broadcast.to(socket.room).emit('newUser', socket.username);
socket.on('disconnect', function(){
socket.broadcast.emit('userLeft', socket.username);
socket.leave(socket.room);
console.log('Connection id: ' + socket.id);
});
});
});
I saw the docs and some sample code it everything seeems to be correct (when it comes simply to syntax) am I missing something simple here?
Thanks!
EDIT
Client code:
var socket, roomname, ioRoom;
var socket = io.connect('http://localhost:3000');
socket.on('enterRoom', function(roomname){
console.log("ENTERED ROOM: " + roomname);
});
socket.on('newUser', function(username){
pushUserName(username);
pushUserStatus(username, ' has joined the room <br/>')
});
socket.on('newRoom', function(data){
alert(data)
});
socket.on('userLeft', function(username){
pushUserStatus(username, ' has left the room <br/>')
})
function pushUserName(username){
var el = document.getElementById("username");
el.innerHTML += username + '<br/>';
}
function pushUserStatus(username, message){
var el = document.getElementById("joined");
el.innerHTML += username + message;
}
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Editor</title>
<style type="text/css" media="screen">
body {
overflow: hidden;
}
#editor {
margin: 0;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
</style>
</head>
<body>
<script src="http://127.0.0.1:8080/socket.io/socket.io.js"> </script>
<script>
(function(){
var getNode = function(s){
return document.querySelector(s);
},
textarea = getNode('.code editor');
try{
var socket = io.connect('http://127.0.0.1:8080');
} catch(e){
}
if(socket !== undefined){
//put latest string in DB to ACE
socket.on('output', function(data){
if(data.length){
var x = data.length-1;
editor.setValue(data[x].code);
}
});
socket.on('code-changes', function(){
editor.on("change", function(data){
var code = editor.getValue();
code = data;
socket.emit('input',{
code: data
});
});
});
/*
// after keydown put new string to DB
editor.on('change', function(data){
var code = editor.getValue();
socket.emit('input',{
code: code
});
});
//if(asciiValue <=0 || asciiValue >= 255){
socket.emit('input',{
code: code
});
console.log("inserted");
*/
}
})();
</script>
<div id="aceEditor" style="height: 500px; width: 500px">some text</div>
<script src="src-noconflict/ace.js" type="text/javascript" charset="utf-8"> </script>
<script>
var editor = ace.edit("aceEditor");
var code = editor.getValue();
//editor.setValue("new code here");
editor.getSession().setValue(editor.getValue(), 1);
editor.setTheme("ace/theme/twilight");
editor.session.setMode("ace/mode/javascript");
</script>
</body>
</html>
Server.js:
var mongo = require('mongodb').MongoClient;
var app = require('express')();
var http = require('http').Server(app);
var client = require('socket.io')(http);//.listen(8080).sockets;
app.get('/', function(req, res){
res.sendFile(__dirname + '/static' + '/index.html');
});
mongo.connect('mongodb://127.0.0.1/code', function(err, db){
if(err) throw err;
client.on('connection', function(socket){
var col = db.collection('messages');
col.find().limit(3).sort({_id: 1}).toArray(function(err, res){
if(err) throw err;
socket.emit('output',res);
});
socket.on('input', function(data){
var code = data.code;
client.emit('output', [data]);
console.log(data);
col.insert({code: code}, function(){
console.log("inserted");
})
});
});
});
http.listen(8080, function(){
console.log('listening on 8080');
});
I having problems sending code from ace editor to mongodb via a socket.emit.
and I'm not why the code is not sending to mongo. I tried to emit the code with editor.getValue(); I'm not sure 100% how editor.on(change) works fully..... Any tips would be much appreciated.
I think you are doing wrong here:
//socket.on('code-changes', function(){ // Editor's changes should not be within socket event handling
editor.on("change", function(data){
var code = editor.getValue();
code = data;
socket.emit('input',{
code: data
});
});
//});
I have the following code:
var room = "1";
var chat = io.connect("localhost:3700/");
self.chat = chat;
chat.on("connection", function(socket){
socket.emit("room", room);
socket.on('message', function (data) {
self.receiveMessage(data);
});
});
chat.broadcast.to(room).emit('send',"HEllo");
receiveMessage:
receiveMessage: function(data){
var $elem = $("#chat1");
var $content = $elem.find(".messageText");
if(data.message) {
messages.push(data);
var html = '';
for(var i=0; i<messages.length; i++) {
html += '<b>' + (messages[i].username ? messages[i].username : 'Server') + ': </b>';
html += messages[i].message + '<br />';
}
$content.html(html);
} else {
console.log("There is a problem:", data);
}
}
The line chat.broadcast.to(room).emit('send',"HEllo"); gives me the error:
Uncaught TypeError: Cannot call method 'to' of undefined
What am I doing wrong?
Not really sure but I think you can send a broadcast only on connection.
You can try this:
var room = "1";
var chat = io.connect("localhost:3700/");
self.chat = chat;
chat.on("connection", function(socket){
socket.emit("room", room);
socket.on('message', function (data) {
self.receiveMessage(data);
});
chat.broadcast.to(room).emit('send',"HEllo");
});
Of course you can also send the broadcast in a separate handler, i.e.:
var room = "1";
var chat = io.connect("localhost:3700/");
self.chat = chat;
chat.on("connection", function(socket){
socket.emit("room", room);
socket.on('message', function (data) {
self.receiveMessage(data);
});
socket.on('foo event', function(data) {
chat.broadcast.to(room).emit('send',"HEllo");
}
});