I'm making a chat app in node.js based on a tutorial from socket.io. The purpose is for a user to enter in a username and a message. The chat will display "username: message". The username text field will then disappear after the first entry. I have it all working except for the chat displaying the message with the username. The chat displays four messages instead of one, they say that both variables are undefined.
JS
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){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
io.on('connection', function(socket){
socket.on('chat message', function(msg, usn){
io.emit('chat message', msg);
io.emit('chat message', usn);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
HTML (Without the style tags)
<!doctype html>
<html>
<head>
<title>Lucas Chat</title>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="u" autocomplete="off" placeholder="Nickname"/><input id="m" autocomplete="off" placeholder="Message"/><button>Send</button>
</form>
<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();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
socket.emit('chat message', $('#u').val());
$('#u').css("display", "none")
$('#m').css("width", "90%")
$('#m').val('');
return false;
});
socket.on('chat message', function(msg, usn){
$('#messages').append($('<li>').text(usn + ": " + msg));
});
</script>
</body>
</html>
clientside
var socket = io();
$('form').submit(function(){
socket.emit('send message', {msg:$('#m').val(),user:$('#u').val()});
$('#u').css("display", "none")
$('#m').css("width", "90%")
$('#m').val('');
return false;
});
socket.on('receive message', function(msg){
$('#messages').append($('<li>').text(msg));
});
and serverside
io.on('connection', function(socket){
socket.on('send message', function(data){
io.emit('receive message',data.msg + ':' + data.user);
});
});
Related
I followed the chat tutorial from socket.io (http://socket.io/get-started/chat/), but once I come to the part I have to get information from the form I get stuck.
The warnings I get from my index.html file are:
io is not defined please fix or add global io
$ is not defined please fix or add global $
I tried adding the website link to the <script src="/socket.io/socket.io.js"> however this had no effect. I am using c9.io as my development tool. using node.js and socket.io.
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(__dirname + '/index.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
http.listen(process.env.PORT, process.env.IP, function() {
console.log("listening on *:" + process.env.PORT);
});
index.html
<!-- I did not include the html and head tags in this example for readability purposes -->
<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 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>
</body>
Add event window ready
var socket = io();
$(document).ready(function(){
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
});
I was trying my hands on Socket.io.
I have the following code.
This is my index.html.
<!doctype html>
<html>
<body>
<ul id="messages"></ul>
<form action="" onsubmit="return sayHello()">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script>
var socket = io.connect('http://127.0.0.1:3001/');
function sayHello(){
var msg = document.getElementById('m');
console.log(msg); <- This is getting printed.
socket.emit('message', msg.value);
msg.value='';
return (false);
}
// $('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>
</body>
</html>
This is my server.js
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){
console.log("GO!") <- This is getting printed
socket.on('chat message', function(msg){
console.log(msg); <- This is not getting printed.
io.emit('chat message', msg);
});
});
http.listen(3001, function(){
console.log('listening on *:3001');
});
I have cloned the sample project from the Socket.io website. I was trying to modify some code by replacing the Jquery with VanillaJS.
You are listening for chat message but emitting message from client. Event name provided with .emit must match with the event name being listened on the server in .on handler.
//SERVER SIDE CODE
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) {
console.log("GO!") < -This is getting printed
socket.on('chat message', function(msg) {
console.log(msg); < -This is not getting printed.
io.emit('chat message', msg);
});
});
http.listen(3001, function() {
console.log('listening on *:3001');
});
<!doctype html>
<html>
<body>
<ul id="messages"></ul>
<form action="" onsubmit="return sayHello()">
<input id="m" autocomplete="off" />
<button>Send</button>
</form>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script>
var socket = io.connect('http://127.0.0.1:3001/');
function sayHello() {
var msg = document.getElementById('m');
console.log(msg); < -This is getting printed.
socket.emit('chat message', msg.value);
//-----------^^^^^^^^^^^^ Event name must match with the `.on` listener on the server!
msg.value = '';
return (false);
}
</script>
</body>
</html>
I'm having this problem even with the Socket.io official chat sample.
I had this set up on AWS. I could only received the 'successfully connected' message on the terminal but not the 'message: ....'. Even with Google Dev Tool I couldn't saw any related error. Anyone could help?
Here's the client side javascript code:
<script src="https://cdn.socket.io/socket.io-1.3.4.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
</script>
Then the server side node.js code:
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');
});
http.listen(8989, function(){
console.log('listening on *:8989');
});
io.on('connection', function(socket){
console.log('successfully connected');
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
});
There is no form submit on button click, also form submit will create a lot of page refreshes and everything, and also you dont need a form for this exercise
Create a function sendMessage()
<script>
var socket = io();
function sendMessage(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
}
</script>
In your HTML remove form and add onclick to button
<body>
<ul id="messages"></ul>
<input id="m" autocomplete="off" /><button onclick="sendMessage()">Send</button>
</body>
It turned out the problem was on the client side javascript code.
I referred to this sample code and found that on socket.io official website it says in some cases (Express 3/4 or the framework) you need to use io.connect() instead of io(). However it works for me in my previous case.
Here's the changed code:
var socket = io.connect();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
I am trying to have it so when a user disconnects from my chat room, it pops up with " has left chat room".
Here is my server code:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('chat/index.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
socket.on('disconnect', function(nickname){
io.emit('disconnect', nickname);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
And here is my client code:
var socket = io();
var nickname;
var leaving;
$('messageForm').submit(function(){
socket.emit('chat message', (nickname + ": " + $('#m').val()));
$('#m').val('');
return false;
});
$('#nicknameForm').submit(function(){
nickname = $('#nickname').val();
if(nickname ==''){
alert("Please enter a value");
}else{
$( "#dialog" ).dialog( "close" );
leaving = nickname + " has left";
}
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
socket.on('disconnect', function(nickname){
socket.emit('disconnect message', nickname);
});
At the moment, nothing appears at all, and I'm not too sure why.
You need to emit a unique event to the clients when another client disconnects.
Change the following:
socket.on('disconnect', function() {
io.emit('disconnect', nickname);
});
To something like this:
socket.on('disconnect', function() {
socket.broadcast.emit('user disconnect', nickname);
});
And add this to your client code:
socket.on('user disconnect', function(nickname){
$('#messages').append($('<li>').text(nickname+' has left the channel.'));
});
I have a little node.js app with sockets. My goal is to have one machine open with my webpage, and a seperate machine open with the same webpage. When I paste text into the page on machine 1, I want that to auto update on machine 2. when i paste text on machine 2, i want that previous text to be erased from machine 1, and be updated with the text from machine 2.
currently i have the page running in two seperate browser windows. in machine 1 i type "a", on machine 2 appears "a".
on machine 1 i type "b", on machine 2 appears "ab". it is constantly appending!
video: http://instagram.com/p/jVIgTZE2Ib/
app.js
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);
});
});
index.html
<textarea id="chat"></textarea>
<!-- <textarea size="35" id="message"></textarea> -->
<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');
$chat.keyup(function(e){
// var code = e.keyCode || e.which;
// if(code == 13) { //Enter keycode
e.preventDefault();
socket.emit('send message', $chat.val());
// }
});
socket.on('new message', function(data){
// $chat.val('');
$chat.append(data + "<br/>");
});
});
</script>
All I had to do was change:
socket.on('new message', function(data){
$chat.append(data + "<br/>");
});
to
socket.on('new message', function(data){
$chat.val(data);
});