How do I stop Socket.io spaming connections? - javascript

I am making a socket.io chat app. When I either start the server or make the first connection it spams the callback. The callback does not stop until the server is stopped. I think the error is coming from the html file, but I'm not exactly sure. Thank you for your time.
IO callback:
io.sockets.on('connection', (socket) =>{
connections.push('socket')
console.log('Connection made \n ' + connections.length + ' made')
socket.on('disconnect', function(data){
connections.splice(connections.indexOf(socket), 1)
console.log('Disconnected: %s sockets left', connections.length)
})
})
My HTML file:
<!DOCTYPE html>
<html>
<head>
<title>Chat App</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
<style>
body{
margin: 30px;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-4">
<div class="well">
<h3>Online Users</h3>
<ul class="list-group" id="users"></ul>
</div>
</div>
<div class="col-md-8">
<div class="chat" id="chat"></div>
<form id="messageForm">
<div class="form-group">
<label>Enter Message</label>
<textarea id="message" class="form-control"></textarea>
<br>
<input type="submit" class="btn btn-primary" value="Send">
</div>
</form>
</div>
</div>
</div>
<script>
var socket = io()
</script>
</body>
</html>

The problem is on line 2. You are pushing string i.e 'socket' to connections. 'socket' doesnot refer to the socket variable in the argument. You need to push socket not 'socket' because its just combinations of letters not variable
io.sockets.on('connection', (socket) =>{
connections.push(socket) // this line is changed
console.log('Connection made \n ' + connections.length + ' made')
socket.on('disconnect', function(data){
connections.splice(connections.indexOf(socket), 1)
console.log('Disconnected: %s sockets left', connections.length)
})
})

Related

My contact form does not work when I deploy my website using firebase but it does when I use local host. My first website so don't know what to do

I followed a video tutorial that told me how to do this using nodemailer. It works perfectly fine when I use "npm run dev" to run it on localhost but after I deployed my website using firebase the alert that tells me in app.js that something went wrong shows up which means that the email has not been sent and I have also checked to see that it hasn't
code in app.js
const contactForm = document.querySelector('.contact-form');
let name = document.getElementById('name');
let email = document.getElementById('email');
let message = document.getElementById('message');
contactForm.addEventListener('submit', (e)=>{
e.preventDefault();
let formData = {
name: name.value,
email: email.value,
message: message.value
}
let xhr = new XMLHttpRequest();
xhr.open('POST', '/');
xhr.setRequestHeader('content-type', 'application/json');
xhr.onload = function(){
console.log(xhr.responseText);
if(xhr.responseText == 'success') {
alert('Email sent');
name.value = '';
email.value = '';
message.value = '';
}else{
alert('something went wrong');
}
}
xhr.send(JSON.stringify(formData));
})
code in server.js
const express = require('express');
const app = express();
const nodemailer = require("nodemailer");
const PORT = process.env.PORT || 2500;
//Middleware
app.use(express.static('webFiles'));
app.use(express.json())
app.get('/', (req, res)=>{
res.sendFile(__dirname + '/webFiles/Contact.html');
})
app.post('/', (req,res)=>{
console.log(req.body);
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'myEmail', -- had to hide these
pass: 'myEmailsPassword'
}
});
const mailOptions = {
from: req.body.email,
to: 'myEmail', -- sorry have to hide this again
subject: `Message from ${req.body.email}`,
text: req.body.message
};
transporter.sendMail(mailOptions, (error, info)=>{
if(error) {
console.log(error);
res.send('error');
}else{
console.log('Email sent: ' + info.response);
res.send('success');
}
});
})
app.listen(PORT, ()=>{
console.log(`Server running on port ${PORT}`);
})
Code in html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="referrer" content="origin">
<link href="https://fonts.googleapis.com/css2?family=Yanone+Kaffeesatz:wght#300&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/all.min.css">
<link rel="stylesheet" href="css/style.css">
<title>Contact Me</title>
</head>
<body>
<div class="loader_bg">
<div class="loader"></div>
</div>
<section class="wrapper">
<div id="stars"></div>
<div id="stars2"></div>
<div id="stars3"></div>
</section>
<div class="container">
<nav>
<h1 class="title">Ajaypartap ;<span> D</span></h1>
<ul>
<li>About Me</li>
<li>Projects</li>
<li>Skills</li>
<li>Contact Me</li>
</ul>
</nav>
</div>
<form id="contact-form" class="contact-form">
<div class="title">
<h2>CONTACT</h2>
</div>
<div class="half">
<div class="item">
<label for="name">NAME</label>
<input type="text" id="name" required="required">
</div>
<div class="item">
<label for="email">EMAIL</label>
<input type="email" id="email" required="required">
</div>
</div>
<div class="full">
<label for="message">MESSAGE</label>
<textarea id="message" required="required"></textarea>
</div>
<div class="action">
<input type="submit" class="submit" value="Send">
<input type="reset" value="Reset">
</div>
<div class="icons">
</div>
</form>
<script src="js/app.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
setTimeout(function(){
$('.loader_bg').fadeOut();
}, 2000);
</script>
</body>
</html>
code directory

Cant load dapp in metamask mobile browser

I have created small ethereum dapp. which is working perfectly fine web browser.
http://slenex.com/slenwallet/
But the same is loading in mobile browser but not interacting with mobile wallet
So i tried in metamask browser, but the app is not loading.
Here is my code:
Is anything I have to do, to work in mobile metamask browser?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/web3/1.2.11/web3.min.js" integrity="sha512-6lf28FmolQdo4ap44cXw7j+thYEZzS1/kXxDkX1ppO//SHCageBS1HmYdqkkL819WfGtQ+7TE+uXEwsxjJXEKQ==" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body class="container">
<h2 class="row col-lg-12" >PAY ETHER USING WALLET THROUGH SMART CONTRACT</h2><div>
<div class="form-group row col-lg-12">
<input class="col-lg-2 form-control" id="pay" type="text" placeholder="Ether to transfer"/>
<button class="col-lg-1 btn btn-success" id="paySm">Pay</button></div>
<div class="alert alert-success success" role="alert"></div>
</div><hr/>
<h3 class="row col-lg-12" >TRANSFER ETHER</h3><div>
<div class="form-group row col-lg-12">
<input class="col-lg-4 form-control" id="addr" type="text" placeholder="Address"/>
<input class="col-lg-2 form-control" id="amt" type="text" placeholder="Ether to transfer"/>
<button class="col-lg-1 btn btn-dark" id="transfer">Transfer</button></div>
<div class="alert alert-dark tx-success" role="alert"></div>
</div><hr/>
<h3 class="row col-lg-12" >CONTRACT BALANCE </h3><div>
<div class="form-group row col-lg-12">
<button class="col-lg-2 btn btn-warning" id="getBal">Get Balance</button></div>
<div class="alert alert-warning bal-success"></div>
</div>
</body>
<script>
var instance;
var web3;
$(document).ready(function() {
$(".success").hide(); $(".bal-success").hide(); $(".tx-success").hide();
if (typeof web3 !== 'undefined') { // alert("web3 detected");
startApp(web3);
}
function startApp(web3) {
window.ethereum.enable();
web3.eth.defaultAccount = web3.eth.accounts[0];
console.log(web3.eth.defaultAccount)
var rinkebyABI= JSON.parse('[{"inputs":[{"internalType":"address payable","name":"addr1","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"fundtransfer","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"payMe","outputs":[{"internalType":"bool","name":"success","type":"bool"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"balance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}]');
EtherContract = web3.eth.contract(rinkebyABI);
var rinkebyInstance = EtherContract.at('0xbB0592720Ed6116dfcda973099E4b484E8D616eB');
// var localABI= JSON.parse('[ { "constant":false,"inputs":[{"name":"addr1","type":"address"},{"name":"amount","type":"uint256"}], "name":"fundtransfer","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false, "inputs":[],"name":"payMe","outputs":[{"name":"success","type":"bool"}],"payable":true,"stateMutability":"payable", "type":"function"},{"constant":true,"inputs":[],"name":"balance","outputs":[{"name":"","type":"uint256"}],"payable": false,"stateMutability":"view","type":"function"}]');
// EtherContract = web3.eth.contract(localABI);
// localInstance = EtherContract.at('0xf40D39645F676367D53819537f449A3228c13D5e');
instance = rinkebyInstance;
}
})
$(document).on("click", "#paySm", function(){
var amt = $("#pay").val();
var wei = parseInt(amt)*1e18;
console.log("Amt: "+ amt);
console.log("Default Account: "+ web3.eth.defaultAccount);
console.log("Wei: "+ wei);
instance.payMe({from: web3.eth.defaultAccount, value: wei},
function(err, transactionHash) {
if (!err) console.log("Hash: "+ transactionHash);
$(".success").text("Paid " + amt + " ether to contract");
$(".success").show();
})
});
$(document).on("click", "#transfer", function(){
var addr = $("#addr").val();
var amt = $("#amt").val();
var wei = parseInt(amt)*1e18;
console.log("To Address: "+ addr);
console.log("Wei: "+ wei);
instance.fundtransfer(addr,wei,{from: web3.eth.defaultAccount},
function(err, transactionHash) {
if (!err) console.log(transactionHash);
$(".tx-success").text("Paid " + amt + " ether to " + addr + " Address" );
$(".tx-success").show();
})
});
$(document).on("click", "#getBal", function(){
instance.balance({from: web3.eth.defaultAccount}, function(err, balance) {
if (!err) console.log(balance);
$(".bal-success").text("Available balance in contract: " + balance/1e18 + " Ether");
$(".bal-success").show();
})
});
</script>
</html>
Kindly Help me. Thanks in advance..
Metamask Mobile app requires that the website have a valid ssl certificate. So just make sure to use https:// rather than http:// when accessing your dapp. Please refer to your specific server config in order to enable https://.

Socket.io stops emitting when any of the window is minimized

I'm trying to build a simple real time text editor that can be accessed and edited by a couple of collaborators at the very same time (not using any lock properties for now). It all works well, transmits live data - until I minimize any of the window (basically using two chrome windows to see the results) and socket stops emitting data.
Here are the server and client -
Server
const express = require("express");
const app = express();
const server = require("http").createServer(app);
const io = require("socket.io").listen(server);
users = [];
connections = [];
server.listen(4000);
console.log("server running");
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
io.sockets.on("connection", socket => {
//Connect
connections.push(socket);
console.log("connected: ", connections.length);
//Disconnect
socket.on("disconnect", data => {
connections.splice(connections.indexOf(socket), 1);
console.log("disconnected! left: ", connections.length);
});
//Send Message
socket.on('send message', data => {
console.log(data);
io.sockets.emit('new message', {msg: data});
});
});
Client
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Chat</title>
<link
href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
crossorigin="anonymous"
/>
</head>
<body>
<div class="container">
<div class="msgArea" id="msgArea">
<div class="row">
<div class="col-md-4">
<div>
<h3>RealTime Editor</h3>
<ul class="list-groups" id="users"></ul>
</div>
</div>
<div class="col-md-8">
<div class="chat" id="chat"></div>
<form action="" id="msg-form">
<div class="form-group">
<label for="">Enter below</label>
<textarea name="" id="msg" rows="15" class="form-control"></textarea>
<br />
</div>
</form>
</div>
</div>
</div>
</div>
</body>
<script src="/socket.io/socket.io.js"></script>
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"
></script>
<script>
$(document).ready(() => {
console.log("connect");
const socket = io.connect();
let $msg = $("#msg");
socket.on("new message", data => {
// $chat.append('<div class="well">' + data.msg + "</div>");
$('#msg').text(data.msg);
});
$("#msg").on("change keyup paste", function() {
socket.emit("send message", $msg.val());
});
});
</script>
</html>

node.js Socket io "Reference error io is not defined"

I'm working on a chat program, I'm still in the beginning of making it but when I try to connect to the server from the console on google chrome it says a reference error io is not defined.
client
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<title>Chat</title>
</head>
<body>
<div class="chat">
<input type="text" class="chat-name" placeholder="Enter your name">
<div class="chat-messages">
<div class="chat-message">
</div>
</div>
<textarea placeholder="type your message" class="chat-textarea"></textarea>
<div class="chat-status">Status: <span>Idle</span></div>
</div>
<script>src="http://localhost:8080/socket.io/socket.io.js"</script>
</body>
</html>
server.js
var mongo = require('mongodb').MongoClient,
client = require('socket.io').listen(8080);
console.log("Server is running on port 8080");
It's because of this:
<script>src="http://localhost:8080/socket.io/socket.io.js"</script>
It's a standard JS import. It should look like this:
<script src="http://localhost:8080/socket.io/socket.io.js"></script>

How to connect to a SignalR hub from PhoneGap app on iOS?

I am attempting to build a PhoneGap iOS client for a basic SignalR chat server I have running (ASP.NET MVC 4). Everything works great when accessing it from a page in a browser but I just can't seem to get it to connect from the PhoneGap app. Here's the relevant parts of my code:
Server global.asax
protected void Application_Start()
{
// Register the default hubs route: ~/signalr * This must be registered before any other routes
RouteTable.Routes.MapHubs(new HubConfiguration { EnableCrossDomain = true });
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
Server web.config
<configuration>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"></modules>
</system.webServer>
</configuration>
Server hub
public class ChatHub : Hub
{
public void Send(string name, string message)
{
Clients.All.broadcastMessage(name, message);
}
}
PhoneGap client
<body>
<div data-role="page">
<div data-role="header">
<h1>Life As A Pixel</h1>
</div><!-- /header -->
<div data-role="content">
<label for="username">Name:</label>
<input type="text" name="username" id="username" value="" />
<label for="message">Message:</label>
<input type="text" name="message" id="message" value="" />
<br>
<input type="button" value="Send" id="sendmessage" />
</div><!-- /content -->
<div data-role="footer" data-position="fixed">
<h4></h4>
</div><!-- /footer -->
</div><!-- /page -->
<script type="text/javascript" src="cordova-2.7.0.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="js/jquery.mobile-1.3.1.js"></script>
<script type="text/javascript" src="js/jquery.signalR-1.0.0-rc1.min.js"></script>
<script type="text/javascript" src="http://www.mysite.com/signalr/hubs"></script>
<script type="text/javascript">
app.initialize();
</script>
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub
jQuery.support.cors = true;
$.connection.hub.url = 'http://www.mysite.com/signalr';
var chat = $.connection.chatHub;
alert(chat);
//alert(chat);
// Create a function that the hub can call to broadcast messages.
//chat.client.broadcastMessage = function (name, message) {
//$('#discussion').append('<li><strong>' + name
// + '</strong>: ' + message + '</li>');
//};
// Set initial focus to message input box.
//$('#message').focus();
// Start the connection.
$.connection.hub.start({ jsonp: true }).done(function () {
alert("connected");
$('#sendmessage').click(function () {
// Html encode display name and message.
var encodedName = $('<div />').text($('#username').val()).html();
var encodedMsg = $('<div />').text($('#message').val()).html();
// Call the Send method on the hub.
chat.send(encodedName, encodedMsg);
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
}).fail(function () {
alert("Failed to connect");
});
});
</script>
</body>
I've been through a ton of sites that talk about bits and pieces of it but can't get it figured out.
Thanks in advance,
Jason
I hope this helps. From here -> http://agilefromthegroundup.blogspot.com/2012/09/getting-signalr-and-phonegap-working.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Chat</title>
<link rel="stylesheet" href="jquery.mobile-1.0.1.css" />
<script type="text/javascript" src="jquery-1.7.1.js"></script>
<script type="text/javascript" src="jquery.mobile-1.0.1.js"></script>
<script type="text/javascript" src="http://jgough/SignalR/Scripts/jquery.signalR-0.5.3.js"></script>
<script type="text/javascript" src="http://jgough/SignalR/signalr/hubs"></script>
<script type="text/javascript" charset="utf-8" src="phonegap-1.4.1.js"></script>
<style type="text/css">
.ui-title
{
font-weight: bold;
}
</style>
<script type="text/javascript">
$(function () {
$.connection.hub.url = "http://jgough/SignalR/signalr";
// Grab the hub by name, the same name as specified on the server
var chat = $.connection.chat;
chat.addMessage = function (message) {
$('#chatMessages').append('<li>' + message + '</li>');
};
$.connection.hub.start({ jsonp: true });
$("#sendChatMessage").click(function () {
var message = $("#chatMessage").val();
console.log("Message: " + message);
chat.send(message);
});
});
</script>
</head>
<body>
<div id="home" data-role="page">
<div data-role="header">
<h1>
Chat!</h1>
</div>
<div data-role="content">
<h2>
Chat your heart out...</h2>
<div>
<textarea id="chatMessage"></textarea>
<br />
<a id="sendChatMessage" data-role="button">Send Chat Message</a>
</div>
<ul id="chatMessages">
</ul>
</div>
<div data-role="footer" data-position="fixed">
Thank you for chatting
</div>
</div>
</body>
</html>

Categories