Socket.io app does not work on phone client - javascript

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?

Related

Problems broadcasting messages with Socket.io

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.

Socket only emits once

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.

Trying to make a chatbot with Express.js and Socket.io

So, I've been trying to write this chat-app for awhile now with Node.js, express,js and socket.io and everything works well. Apart from the fact that I'm trying to include a bot called Steve. Steves purpose is to welcome you to the chat, or to have him join after you've joined and introduce himself. As well as beeing able to reply to some "commands". Hi, How are you etc. Etc.
But that part is somethin that I can't get to work.
I'm not asking of you to write the code for me. But if you could please tell me if I'm on the right track and maybe come with some ideas, tips etc. I'm stuck.
Thanks in advance.
Here's my index.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
users = [];
connections = [];
server.listen(process.env.PORT || 3000);
console.log('Server running...');
app.use(express.static(__dirname + '/public'));
app.get('/public', function(req, res) {
res.sendFile(__dirname + 'index.html')
});
io.sockets.on('connection', function(socket) {
connections.push(socket);
console.log('Connected: %s sockets connected', connections.length);
// Disconnect
socket.on('disconnect', function(data) {
users.splice(users.indexOf(socket.username), 1);
updateUsernames();
connections.splice(connections.indexOf(socket), 1);
console.log('Disconnected: %s sockets connected', connections.length);
});
// Send Message
socket.on('send message', function(data) {
io.sockets.emit('new message', {msg: data, user: socket.username});
});
<code>
// New User
socket.on('new user', function(data, callback){
callback(true);
socket.username = data;
users.push(socket.username);
updateUsernames();
});
function updateUsernames() {
io.sockets.emit('get users', users);
}
});
And here's my script.js
$(function () {
var socket = io.connect();
var $messageForm = $('#messageForm');
var $message = $('#message');
var $chat = $('#chat');
var $messageArea = $('#messageArea');
var $userFormArea = $('#userFormArea');
var $userForm = $('#userForm');
var $users = $('#users');
var $username = $('#username');
var name = 'Steve', adress = 'localhost:3000', socket;
function join(){
socket.on('new user', name);
socket.emit('message', "Hi! I am Steve. Steve the Chatter!");
socket.on('new message', listener);
};
function listener(data){
if(data.message=='Hi')
socket.emit('message', 'Hi, '+$username+'.');
};
join();
$messageForm.submit(function(e) {
e.preventDefault();
socket.emit('send message', $message.val());
$message.val('');
});
socket.on('new message', function(data) {
$chat.append('<div class="well"><strong>'+data.user+'</strong>: '+data.msg+'</div>');
});
$userForm.submit(function(e) {
e.preventDefault();
socket.emit('new user', $username.val(), function(data) {
if(data) {
$userFormArea.hide();
$messageArea.show();
}
});
$username.val('');
});
socket.on('get users', function(data) {
var html = '';
for(i = 0;i < data.length;i++){
html += '<li class="list-group-item">'+data[i]+'</li>'
;
}
$users.html(html);
});
});

Cant retrieve simple broadcast message in the HTML file using NodeJS/Socket.io

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 :-)
});

Socket IO not receiving emit data after reconnect

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));
});
}

Categories

Resources