may i know which part of the code that cause after the client disconnect and reconnect the chat message no longer show on the client browser, however the chat is still emit to server and other user will be able to see the message, just the original sender itself won't able to receive the message. I wonder it is socket issue or javascript issue?
Thanks in advance and sorry for my bad english :)
Socket IO Version 1.3.7
Notes: I am integrating the chat with laravel so will not use any nodejs routing here, i guess it wont cause any problem for me right since the chat is able to function normally...just the problem above i currently facing now
//server.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket){
//console.log('a user connected: ' + socket.id);
socket.on('disconnect', function(){
console.log( socket.name + ' has disconnected from the chat.' + socket.id);
io.emit('user', io.sockets.sockets.length);
io.emit('chat message', socket.name + ' has disconnected from the chat.');
});
socket.on('join', function (name) {
socket.name = name;
console.log(socket.name + ' joined the chat.'+ socket.id);
io.emit('user', io.sockets.sockets.length);
io.emit('chat message', socket.name + ' joined the chat.');
});
socket.on('chat message', function(msg){
io.emit('chat message', msg);
console.log(msg);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
''
//Client code here
<div class="board" style="position: absolute;right:40%;width:350px;height:500px;" id="liveQuickAskDesk">
<h2 class="timberGradient">Live Quick Ask Desk</h2>
<div id="innerQuickAskDesk">
<span id="total_user"></span> staff online currently
<button type="button" id="disconnect" class="btn btn-danger">Offline</button>
<div class="col-lg-12" id="messagewindow" style="position: absolute;height:330px;overflow: auto;">
<span id="messages"></span>
</div>
<div class="col-lg-12">
<form style="position: absolute;margin:110% 0 0 0;width:320px;">
<div class="form-group">
<label>Message:</label>
<input type="text" class="form-control" id="m">
</div>
</form>
</div>
</div>
<div class="col-lg-12 center-block" id="connect_div">
<button type="button" id="connect" class="btn btn-primary center-block" style="margin-top: 50%;">Online</button>
</div>
<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>
$("#connect_div").hide();
var socket = io.connect('http://localhost:3000');
var name = "<?php echo $user_name ?>";
$('#disconnect').click(function(){
socket.disconnect();
$("#liveQuickAskDesk").css('background', 'rgba(0,0,0,0.1)');
$("#innerQuickAskDesk").hide();
$("#connect_div").show();
$('#messages').html("");
});
$('#connect').click(function(){
socket = io.connect('http://localhost:3000',{'forceNew':true});
socket.on('connect', function(msg){
socket.emit('join', name);
console.log("client reconnect to the server");
});
$("#liveQuickAskDesk").css('background', 'rgba(0,0,0,0)');
$("#connect_div").hide();
$("#innerQuickAskDesk").show();
});
socket.on('connect', function(msg){
socket.emit('join', name);
console.log("client join the server");
});
socket.on("disconnect", function(){
console.log("client disconnected from server");
});
$('form').submit(function(){
$('#messagewindow').animate({ scrollTop:$('#messagewindow').prop('scrollHeight')}, 10);
socket.emit('chat message', "Staff "+name+": "+$('#m').val());
$('#m').val('');
return false;
});
socket.on('user', function(msg){
$('#total_user').html(msg);
});
socket.on('chat message', function(msg){
$('#messages').append($('<p>').text(msg));
});
</script>
</div>
You are losing your listeners when disconnect and reconnect, so keeping your listeners inside a function and calling it each time you connect should be ok.
socket = io.connect('http://localhost:3000',{'forceNew':true});
setevts();
function setevts () {
socket.on('connect', function(msg){
socket.emit('join', name);
console.log("client join the server");
});
socket.on("disconnect", function(){
console.log("client disconnected from server");
});
socket.on('user', function(msg){
$('#total_user').html(msg);
});
socket.on('chat message', function(msg){
$('#messages').append($('<p>').text(msg));
});
}
Related
I am trying to output a message of 'XYZ is typing' whenever a user begins typing but I can't seem to fix my code. I feel as if the 'socket.broadcast.emit' in the App.JS of my code is the issue but I am not sure. If possible can somebody point me in the right direction to helping me fix my chat app. Thanks in advance!
Index.HTML
<!doctype html>
<html>
<head>
<title>Chit Chat</title>
<link rel="stylesheet" href="/css/styles.css">
</head>
<body>
<ul id="messages"></ul>
<div id="typing"></div>
<form action="">
<input id="username" placeholder="Username" type="text" />
<input id="message-box" autocomplete="off" type="text" placeholder="Type Message" />
<button id="button">Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="/js/scripts.js" charset="utf-8"></script>
</body>
</html>
App.JS (Server)
var express = require('express');
var app = require('express')();
var bodyParser = require('body-parser');
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}))
app.use(express.static('./public'));
app.get('/', function(req, res){
res.sendFile(__dirname + '/views/index.html');
});
var port = process.env.PORT || 3000;
http.listen(port, function(){
console.log('listening on ' + port);
});
// Socket.io
io.on('connection', function(socket) {
// when the client emits 'new message', this listens and executes
socket.on('new message', function(data) {
// we tell the client to execute 'new message'
io.sockets.emit('new message', data);
});
// when the client emits 'typing', we broadcast it to others
socket.on('typing', function(data){
socket.broadcast.emit('typing', data);
});
});
Scripts.JS
console.log('Loaded');
var socket = io();
$(function (){
chat();
emitEvents();
isTyping();
});
function chat() {
$('form').submit(function(e){
var message = {
username: $('#username').val(),
message: $('#message-box').val()
}
e.preventDefault();
socket.emit('new message', message);
$('#message-box').val('');
});
}
function isTyping() {
$('#message-box').keypress(function() {
socket.emit('typing', $('#username').val());
});
}
function emitEvents() {
socket.on('typing', function(data){
console.log(data);
$('#typing').append($('<p>').text(data + 'is typing'));
});
socket.on('new message', function(data){
$('#messages').append($('<li>').text(data.username + ': ' +
data.message));
});
}
I tried your code and it's working. I have created a live example.
I made 2 modifications in scripts.js, so the typing message will appear only once during the typing.
function emitEvents() {
socket.on('typing', function(data){
console.log(data);
$('#typing').html($('<p>').text(data + ' is typing')); // update
});
socket.on('new message', function(data){
$('#typing').html($('<p>').text('')); // update
$('#messages').append($('<li>').text(data.username + ': ' + data.message));
});
}
The code socket.broadcast.emit means sending to all clients except sender.
Check out the Socket.IO cheatsheet.
The code below only emits the data only once. I am not sure it even emits it once as I believe the data is not being sent correctly from frontend(angular 2) to the backend(nodeJs).
frontend code of chat.component.ts:
ngOnInit() {
const sendData = {
username: this.username,
message: this.message
};
const socket = socketIo('http://localhost:3000');
socket.emit('chat message', {
username: 'sendData.username',
message: sendData.message
});
socket.on('chat message', function(msg){
const messageArea = document.getElementById('output');
messageArea.innerHTML +="<strong>" + socket.username + "</strong> : " + socket.message + "\n";
console.log(msg.username + 'lmemons');
});
}
the code of backend:
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
socket.on('chat message', function(msg){
console.log('///////////////////////////////');
io.emit('chat message', msg.username + ': ' + msg.message);
console.log('--------------------------');
});
});
the code runs once which is shown by the console.logs. it only comes out as undefined each time.
I have tried to use the:
socket.on('chat message', function(msg){...
outside of
io.on('connection', function(socket){
but it has errors with the socket claiming that it is undefined.
Essentially I want to append the data onto every all connected sockets' text area.
I was using this https://socket.io/get-started/chat/ tutorial for help.
I have a socket.io app that works perfectly on chrome, safari and opera, with notifications made using push.js.
</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://cdn.rawgit.com/Nickersoft/push.js/master/push.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
var socket = io();
var username = prompt("What's your name?");
var notification = new Audio('https://cdn.rawgit.com/InfiniaPress/Passenger-Pigeon/master/assets/notification.mp3');
if(username){
socket.emit('connection info', username);
}
function send(message) {
$('#messages').append($('<li>').text(message));
}
socket.on('user add', function(usr){
send(usr.username + " has joined.");
});
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('user left', function(usr){
send(usr.username + " has disconnected.");
})
socket.on('chat message', function(msg, usr){
Push.create('Passenger Pigeon', {
body: usr.username + ": " + msg,
icon: "https://cdn.rawgit.com/InfiniaPress/Passenger-Pigeon/master/assets/pigeon-final.png",
timeout: 4000,
onClick: function () {
window.focus();
this.close();
},
vibrate: [200, 100, 200, 100, 200, 100, 200]
});
notification.play();
send(usr.username + ": " + msg);
});
</script>
</body>
</html>
The above is my client side.
var express = require('express'); // Get the module
var app = express(); // Create express by calling the prototype in var express
var http = require('http').Server(app);
var io = require('socket.io')(http);
// Import events module
var events = require('events');
// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();
var config = require('./config.json');
app.get('/', function(req, res){
res.sendFile(__dirname + '/view/index.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg, {username: socket.username});
});
socket.on('connection info', function(usr){
socket.username = usr;
io.emit('user add', {username: usr});
});
});
io.on('connection', function(socket){
console.log('Passenger Pigeon >> a user connected');
socket.on('disconnect', function(){
socket.broadcast.emit('user left', {
username: socket.username,
});
console.log('Passenger Pigeon >> user disconnected');
});
});
http.listen(process.env.PORT || config.port, function(){
console.log('listening on *:' + config.port);
});
^that is my server side.
When I open the app on mobile the [username] has joined prints out, but all messages do NOT appear on the client side. Other computers receive the messages. Why is this so?
I am studying NodeJS together with Socket.io
I have a very simple chat page. But I don't know where's my error.
Here's my simple code:
index.js
var express = require('express');
var app = express();
app.use('/', express.static(__dirname + '/'));
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
//res.send('<h1>Hello World</h1>');
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
//console.log('a user is connected!');
socket.on('disconnect', function() {
//console.log('user disconnected!');
});
socket.on('chat message', function(msg) {
io.emit('chat message: ' + msg);
});
});
http.listen(3000, function() {
console.log('listening on *:3000');
});
index.html
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="on" /><button>Send</button>
</form>
<script type="text/javascript" src="jquery-1.12.4.js"></script>
<script src="/socket.io/socket.io.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) {
console.log(msg); //NO VALUE?
});
</script>
</body>
I can't get the value on this line:
socket.on('chat message', function(msg) {
console.log(msg); //NO VALUE?
});
The message can not be received on the client because, with
// Server: Receive and send message
socket.on('chat message', function(msg) {
io.emit('chat message: ' + msg);
}
you emit an event named chat message: ${msg}, but this is an event you are not listening on the client side.
When emitting an event you do this by defining the event name first, and then specifying the data as second parameter in JSON format. Changing the code above to
// Server: Receive and send message
socket.on('chat message', function(data) {
io.emit('chat message', { message : data.message });
}
will emit the event to the client with the message as the data. Same syntax applies, when sending the event from the client to the sever. So change
// Client: Send message
$('form').submit(function() {
socket.emit('chat message', $('#m').val());
to
// Client: send message
$('form').submit(function() {
socket.emit('chat message', {message : $('#m').val()});
When the server answers your event, you can then receive and access the message as follows:
// Client: Receive message
socket.on('chat message', function(data) {
console.log(data.message); // VALUE :-)
});
After I am passing any string value the server is getting disconnected. The server only accept number in node.js.
io = sio.listen(server);
io.sockets.on('connection', function(socket){
socket.on('chat message', function(msg){
if ((new String(msg)).toString('utf-8') === 'utf-8') {
socket.send(msg);
console.log("Bye bye!\n");
socket.disconnect();
} else {
console.log('Received: ', msg);
messages.push(msg);
io.sockets.emit('chat message', msg);
}
});
I tried this code. But it is not working. Please help me.
var socket = io.connect('http://localhost:8000');
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val();
return false;
});
var datavar=1;
socket.on('chat message', function(msg){
$('#messages').append(msg); });
this is client side code...