Socket.io error - ERR_CONNECTION_TIMED_OUT - javascript

I am trying to build a basic chat html program.
I have set up a node server to test it, however, when accessing the html page, I get an socket error. It's my first time working with node.js and setting up node server, so I've surely done something wrong.
Thanks to everyone who's taking a look at this!
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require("socket.io").listen(server);
var socket = io.listen(1223, "1.2.3.4");
server.listen(process.env.PORT || 3000);
console.log('Server is running...');
var people = {};
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
})
// When connecting
socket.on("connection", function(client) {
client.on("join", function(name){
people[client.id] = name;
client.emit("update", "You have connected to the server.");
socket.sockets.emit("update", name + " has joined the server.");
socket.sockets.emit("update-people", people);
});
// When sending
client.on("send", function(msg){
socket.sockets.emit("chat", people[client.id], msg);
});
// When disconnecting
client.on("disconnect", function(){
socket.sockets.emit("update", people[client.id] + " has left the server.");
delete people[client.id];
socket.sockets.emit("update-people", people);
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
</head>
<script>
$(document).ready(function(){
var socket = io.connect("1.2.3.4:1223");
$("#chat").hide();
$("#name").focus();
$("form").submit(function(event){
event.preventDefault();
});
$("#join").click(function(){
var name = $("#name").val();
if (name != "") {
socket.emit("join", name);
$("#login").detach();
$("#chat").show();
$("#msg").focus();
ready = true;
}
});
$("#name").keypress(function(e){
if(e.which == 13) {
var name = $("#name").val();
if (name != "") {
socket.emit("join", name);
ready = true;
$("#login").detach();
$("#chat").show();
$("#msg").focus();
}
}
});
socket.on("update", function(msg) {
if(ready)
$("#msgs").append("" + msg + "");
})
socket.on("update-people", function(people){
if(ready) {
$("#people").empty();
$.each(people, function(clientid, name) {
$('#people').append("" + name + "");
});
}
});
socket.on("chat", function(who, msg){
if(ready) {
$("#msgs").append("" + who + " says: " + msg + "");
}
});
socket.on("disconnect", function(){
$("#msgs").append("The server is not available");
$("#msg").attr("disabled", "disabled");
$("#send").attr("disabled", "disabled");
});
// Sending the message (either by button click or enter)
$("#send").click(function(){
var msg = $("#msg").val();
socket.emit("send", msg);
$("#msg").val("");
});
$("msg").keypress(function(e){
if (e.which == 13) {
var msg = $("msg").val();
socket.emit("send", msg);
$("#msg").val("");
}
});
});
</script>
<body>
<div class="container">
<div class="row">
<div class="span2">
<ul id="people" class="unstyled"></ul>
</div>
<div class="span4">
<ul id="msgs" class="unstyled">
</div>
</div>
<div class="row">
<div class="span5 offset2" id="login">
<form class="form-inline">
<input type="text" class="input-small" placeholder="Your name" id="name">
<input type="button" name="join" id="join" value="Join" class="btn btn-primary">
</form>
</div>
<div class="span5 offset2" id="chat">
<form id="2" class="form-inline">
<input type="text" class="input" placeholder="Your message" id="msg">
<input type="button" name="send" id="send" value="Send" class="btn btn-success">
</form>
</div>
</div>
</div>
</body>
</html>

You mixed up the different listen calls.
var server = require('http').createServer(app);
var io = require("socket.io").listen(server);
var socket = io.listen(1223, "1.2.3.4");
server.listen(process.env.PORT || 3000);
The third line has not the effect you expect. io is not listening itself. It uses the http server that is listening on port 3000.
Rather use this on the server
var server = require('http').createServer(app);
var socket = require("socket.io").listen(server);
server.listen(process.env.PORT || 3000);
And in the client connect to port 3000 (or the port configured via the PORT environment variable.
var socket = io.connect("your.domain:3000");
If you want to listen on a dedicated port for socket.io, you have to create a second http server listening on a second port, and bind that one to socket.io.

Related

Socket.io Run in Webhost

Im currently new in setting up webhost server and Im studying socket.io and I would like to run it in live server, unfortunately it doesnt work. How do I set this up? I dont have a single Idea how.
It works in my local but not in webserver https://kimmychatroom.000webhostapp.com/
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Websocket 101</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.dev.js"></script>
<link href="/styles.css" rel="stylesheet">
</head>
<body>
<div id="mario-chat">
<h2>Mario Chat</h2>
<div id="chat-window">
<div id="output"></div>
<div id="feedback"></div>
</div>
<input id="handle" type="text" placeholder="Handle" />
<input id="message" type="text" placeholder="Message" />
<button id="send">Send</button>
</div>
<script src="/chat.js"></script>
</body>
</html>
chat.js
// make connection
var socket = io.connect('http://localhost:4000');
//Query Dom
var message = document.getElementById('message'),
handle = document.getElementById('handle'),
btn = document.getElementById('send'),
output = document.getElementById('output'),
feedback = document.getElementById('feedback');
// emit events
btn.addEventListener('click', function(){
socket.emit('chat',{
message: message.value,
handle: handle.value
})
});
message.addEventListener('keypress', function(){
socket.emit('typing', handle.value)
});
// listen for events
socket.on('chat', function(data){
feedback.innerHTML = '';
output.innerHTML +='<p><strong>' + data.handle + ': </strong>' + data.message + '</p>';
})
socket.on('typing', function(data){
feedback.innerHTML = '<p><em>' + data + ' is typing a message... </em></p>';
});
index.js EDITED
// install npm install nodemon -g
// run nodemon index to run server to gitbash
// https://www.youtube.com/watch?v=vQjiN8Qgs3c&list=PL4cUxeGkcC9i4V-_ZVwLmOusj8YAUhj_9
// install socket.io - npm install socket.io --save
var express = require('express');
var socket = require('socket.io');
// App setup
var app = express();
let port= process.env.PORT || 4000;
var server = app.listen(port, function(){
console.log(`listening to request on port ${port}`);
});
// Static Files
app.use(express.static('public'));
// Socket setup
var io = socket(server);
io.on('connection', function(socket){
console.log('made socket connection', socket.id)
socket.on('chat', function(data){
io.sockets.emit('chat', data);
})
socket.on('typing', function(data){
socket.broadcast.emit('typing', data)
})
});
I dont have the slightest idea what to change in chat.js socket variable and index.js server variable
var socket = io.connect('http://localhost:4000'); Here you should not provide the URL of the localhost while you deploy your application. While deploying you should use the URL or the webserver. Or if you are using the default namespace /, then there is no need of using a URL even in the localhost. Your code should be like this,
//changes here
var socket = io()
//Query Dom
var message = document.getElementById('message'),
handle = document.getElementById('handle'),
btn = document.getElementById('send'),
output = document.getElementById('output'),
feedback = document.getElementById('feedback');
// emit events
btn.addEventListener('click', function(){
socket.emit('chat',{
message: message.value,
handle: handle.value
})
});
message.addEventListener('keypress', function(){
socket.emit('typing', handle.value)
});
// listen for events
socket.on('chat', function(data){
feedback.innerHTML = '';
output.innerHTML +='<p><strong>' + data.handle + ': </strong>' + data.message + '</p>';
})
socket.on('typing', function(data){
feedback.innerHTML = '<p><em>' + data + ' is typing a message... </em></p>';
});

Socket IO randomly send number when idle

i am facing an issue about socket io random send number when idle..
chat.js:
$(document).ready(function(){
var socket = io();
socket.emit("handshaking","");
$('.input').keypress(function (e) {
if (e.which == 13) {
var msg = $('.input').val();
if(msg !=""){
socket.emit("sendMessage",msg);
$('.chat-box').append("<p class='msgSend'>"+msg+"</p><br>");
$('.input').val('');
}
}
});
//If handshaking success, print a message to chat box
socket.on("pong", function(msg){
$('.chat-box').append("<p class='systemMsg'>" + msg + "</p><br>");
});
//Player message
socket.on("getMessage",function(msg){
$('.chat-box').append("<p class='msgReceive'>"+msg+"</p><br>");
});
});
server.js:
var app = require('http').createServer(handler);
var io = require('socket.io')(app);
var path = require('path');
var mime = require('mime');
var fs = require('fs');
var cache = {};
app.listen(80,function(){
console.log("Listening to port 80.");
});
function send404(res){
res.writeHead(404,{'content-type': 'text/plain'});
res.write('Error 404: resource not found.');
res.end();
}
function sendFile(res, filePath, contents){
res.writeHead(200,{"content-type": mime.getType(path.basename(filePath))});
res.end(contents);
}
function serverStatic(res, cache, path){
if(cache[path]) {
sendFile(res, path, cache[path]);
} else {
fs.exists(path, function(exists) {
if(exists) {
fs.readFile(path, function(err,data) {
if(err) {
send404(res);
} else {
cache[path] = data;
sendFile(res,path,data);
}
});
} else {
send404(res);
}
});
}
}
function handler (req, res) {
var filePath;
if(req.url == '/'){
filePath = 'public/index.html';
console.log(filePath);
} else {
filePath = 'public' + req.url;
console.log(filePath);
}
var path = './' + filePath;
serverStatic(res, cache, path);
}
io.on('connection', function (socket) {
socket.on('disconnect', function(){
console.log('user disconnected');
socket.broadcast.emit("pong","A user has leave the room.");
});
socket.on("handshaking",function(msg){
console.log("A user is joined.");
socket.broadcast.emit("pong", "A user has join the room.");
});
socket.on("sendMessage",function(msg){
socket.broadcast.emit("getMessage",msg);
});
});
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Chat System</title>
<link rel="stylesheet" type="text/css" href="/css/style.css">
</head>
<body>
<div class="chat-area">
<div class="chat-box"></div>
<input class="input" style="width:100%;" placeholder="Type something"> <!--<button style="">SEND</button>-->
</div>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.slim.js"></script>
<script src="/js/chat.js" type="text/javascript"></script>
</body>
</html>
I am not sure what's wrong with these code but i am sure that all is working except it will auto send some random number when i idle the browser (the page is still on).
Can someone help me take a look on this issue?
Thank you!

How can I connect to MongoDB using other device(s) accessing the locally hosted chat app?

I have a simple chat application built using sockets,MongoDB,Express.
The application works fine when hosted on my local machine (localhost:4000).
I am able to connect to MongoDB and send and receive messages.
Issue : But when I open the app on my phone browser using the PC IP address (e.g. 192.168.1.108:4000). I can see the index.html page , but unable to send and receive messages and load previous messages from mongodb.
//server.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
connections = [];
app.use(express.static(__dirname + '/public'));
server.listen(process.env.PORT || 4000);
console.log('Server Running');
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
const mongo = require('mongodb').MongoClient;
const client = require('socket.io').listen(server).sockets;
// Connect to mongo
mongo.connect('mongodb://127.0.0.1/mongochat', function(err, db){
if(err){
throw err;
}
console.log('MongoDB connected...');
// Connect to Socket.io
client.on('connection', function(socket){
let chat = db.collection('chats');
// Create function to send status
sendStatus = function(s){
socket.emit('status', s);
}
// Get chats from mongo collection
chat.find().limit(100).sort({_id:1}).toArray(function(err, res){
if(err){
throw err;
}
// Emit the messages
socket.emit('output', res); //whenever we have to pass from server to client(index.html) , we do .emit()
});
// Handle input events
socket.on('input', function(data){
let name = data.name;
let message = data.message;
// Check for name and message
if(name == '' || message == ''){
// Send error status
sendStatus('Please enter a name and message');
} else {
// Insert message
chat.insert({name: name, message: message}, function(){
client.emit('output', [data]);
// Send status object
sendStatus({
message: 'Message sent',
clear: true
});
});
}
});
// Handle clear
socket.on('clear', function(data){
// Remove all chats from collection
chat.remove({}, function(){
// Emit cleared
socket.emit('cleared');
});
});
});
});
<!-- Index.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">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<title>MongoChat</title>
<style>
#messages{height:300px;}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3 col-sm-12">
<h1 class="text-center">
MongoChat
<button id="clear" class="btn btn-danger">Clear</button>
</h1>
<div id="status"></div>
<div id="chat">
<input type="text" id="username" class="form-control" placeholder="Enter name...">
<br>
<div class="card">
<div id="messages" class="card-block">
</div>
</div>
<br>
<textarea id="textarea" class="form-control" placeholder="Enter message..."></textarea>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<script>
(function(){
var element = function(id){
return document.getElementById(id);
}
// Get Elements
var status = element('status');
var messages = element('messages');
var textarea = element('textarea');
var username = element('username');
var clearBtn = element('clear');
// Set default status
var statusDefault = status.textContent;
var setStatus = function(s){
// Set status
status.textContent = s;
if(s !== statusDefault){
var delay = setTimeout(function(){
setStatus(statusDefault);
}, 4000);
}
}
// Connect to socket.io
var socket = io.connect('http://127.0.0.1:4000');
// Check for connection
if(socket !== undefined){
console.log('Connected to socket...');
// Handle Output
socket.on('output', function(data){
//console.log(data);
if(data.length){
for(var x = 0;x < data.length;x++){
// Build out message div
var message = document.createElement('div');
message.setAttribute('class', 'chat-message');
message.textContent = data[x].name+": "+data[x].message;
messages.appendChild(message);
messages.insertBefore(message, messages.firstChild);
}
}
});
// Get Status From Server
socket.on('status', function(data){
// get message status
setStatus((typeof data === 'object')? data.message : data);
// If status is clear, clear text
if(data.clear){
textarea.value = '';
}
});
// Handle Input
textarea.addEventListener('keydown', function(event){
if(event.which === 13 && event.shiftKey == false){
// Emit to server input
socket.emit('input', {
name:username.value,
message:textarea.value
});
event.preventDefault();
}
})
// Handle Chat Clear
clearBtn.addEventListener('click', function(){
socket.emit('clear');
});
// Clear Message
socket.on('cleared', function(){
messages.textContent = '';
});
}
})();
</script>
</body>
</html>
Try binding the http server on 0.0.0.0 through server.listen(process.env.PORT || 4000, '0.0.0.0') and also in your index.html you got
var socket = io.connect('http://127.0.0.1:4000');
which should actually be your internal ip.

PeerJS Connection made, but no data transfer

I've been trying to get two browsers communicate with each other using PeerJS, however am unable to overcome this hurdle.
As far as I can tell, the chrome console indicates that a successful connection has been established between the two browsers, however I cannot get either client to receive any data.
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<script src="http://cdn.peerjs.com/0.3/peer.min.js"></script>
<script src="peer.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<label id="yourID">Your ID is: </label><br>
<label id="currentConn">You are currently connected to: </label>
<div>
<button id="connectButton">Connect to this ID</button>
<input type="text" id="toConnectID">
</div>
<hr>
<div>
<textarea id="playArea"></textarea><br>
<button id="sendMessage">Send Message</button>
</div>
<script>
console.log("JS Started");
var peer1 = new Peer({key: 'lwjd5qra8257b9', debug: 3});
document.getElementById("connectButton").disabled = true;
document.getElementById("sendMessage").disabled = true;
peer1.on('open', function(id){
console.log("Peer1 ready");
document.getElementById("connectButton").disabled = false;
document.getElementById("yourID").innerHTML = "Your ID is: "+id;
peer1.on('data', function(data){
console.log("Data received: "+data);
document.getElementById("playArea").value = data;
});
});
peer1.on('connection', function(dataConnection){
document.getElementById("sendMessage").disabled = false;
document.getElementById("currentConn").innerHTML = "You are currently connected to: "+dataConnection.peer;
conn = dataConnection;
});
$("#connectButton").click(function(){
ID = document.getElementById("toConnectID").value;
conn = peer1.connect(ID);
document.getElementById("currentConn").innerHTML = "You are currently connected to: "+ID;
document.getElementById("sendMessage").disabled = false;
});
$("#sendMessage").click(function(){
text = document.getElementById("playArea").value;
conn.send(text);
console.log("Data sent: "+text);
});
</script>
</body>
</html>
The end goal is to have the browsers communicate over a local network, so code is purely to test the PeerJS library.
Any help would be much appreciated.
your on('data') subscriber should be under conn.on('data') instead of peer1.on('data') .
and you need conn.on('data') in 2 places to be able to receive data in both end. One for the client who establish connection itself, under conn.on('data'), one for the client who got connected, under peer1.on('connection'). If you remove any1 of them, you will see only one end is receiving data.
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<script src="http://cdn.peerjs.com/0.3/peer.min.js"></script>
<script src="peer.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<label id="yourID">Your ID is: </label><br>
<label id="currentConn">You are currently connected to: </label>
<div>
<button id="connectButton">Connect to this ID</button>
<input type="text" id="toConnectID">
</div>
<hr>
<div>
<textarea id="playArea"></textarea><br>
<button id="sendMessage">Send Message</button>
</div>
<script>
console.log("JS Started");
var peer1 = new Peer({key: 'lwjd5qra8257b9', debug: 3});
document.getElementById("connectButton").disabled = true;
document.getElementById("sendMessage").disabled = true;
var conn;
peer1.on('open', function(id){
console.log("Peer1 ready");
document.getElementById("connectButton").disabled = false;
document.getElementById("yourID").innerHTML = "Your ID is: "+id;
});
peer1.on('connection', function(dataConnection){
document.getElementById("sendMessage").disabled = false;
document.getElementById("currentConn").innerHTML = "You are currently connected to: "+dataConnection.peer;
conn = dataConnection;
conn.on('data', function(data){
console.log("Data received: "+data);
document.getElementById("playArea").value = data;
});
console.log("Connected")
});
$("#connectButton").click(function(){
ID = document.getElementById("toConnectID").value;
conn = peer1.connect(ID);
conn.on('open',function(){
console.log("open")
conn.on('data', function(data){
console.log("Data received: "+data);
document.getElementById("playArea").value = data;
});
})
document.getElementById("currentConn").innerHTML = "You are currently connected to: "+ID;
document.getElementById("sendMessage").disabled = false;
});
$("#sendMessage").click(function(){
text = document.getElementById("playArea").value;
conn.send(text);
console.log("Data sent: "+text);
});
</script>
</body>
</html>

Socket.io is not defined

Whenever I go to http://localhost:8080/search (search.html), it loads all of the html, then it reaches the client-side javascript and crashes. The first console.log in searchClient.js works, but not the second. The error is that io is not defined.
server.js:
var http = require('http');
var express = require('express');
var anyDB = require('any-db');
var engines = require('consolidate');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var conn = anyDB.createConnection('sqlite3://riverdata.db');
app.engine('html', engines.hogan);
app.set('views', __dirname + '/templates');
app.use(express.static(__dirname + '/public'));
app.get("/", function(request, response){
response.render('home.html');
});
app.get("/search", function(request, response){
response.render('search.html');
});
io.on('connection', function(socket){
socket.on('join', function(){
});
socket.on('search', function(toShowList, conditionsList){
var data = conn.query('SELECT toShowList FROM riverdata WHERE conditionsList');
console.log("im in socket.on(search)");
socket.emit('data', data);
});
socket.on('disconnect', function(){
});
});
app.listen(8080);
searchClient.js:
console.log("begins");
var socket = io.connect();
console.log("keeps running");
window.addEventListener('load', function(){
console.log("page loads");
var search = document.getElementById("searchButton");
submit.addEventListener("click", search, false);
socket.emit('join');
socket.on('data', function(data){
console.log(data);
})
}, false);
function search(){
console.log("button clicked");
var toShowList = [];
var conditionsList = [];
socket.emit('search', toShowList, conditionsList);
}
search.html:
<!DOCTYPE HTML PUBLIC>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src='localhost:8080/socket.io/socket.io.js'></script>
<script type="text/javascript" src="/searchClient.js"></script>
<title>Envirostats Database</title>
<link rel="stylesheet" href="/style.css" type="text/css" />
</head>
<body class="search">
<form action="">
<input type="checkbox" name="data" value="data"> Show Date <br>
<input type="checkbox" name="data" value="river"> Show River <br>
</form>
<button id=searchButton> Search </button>
</body>
</html>

Categories

Resources