Logging connects and disconnects with socket.io - javascript

I'm writing a pretty simple app (for now) and I need to log each connection and disconnection inside a div. Currently I can log every connection and disconnection on my console with the code I have but do to my limited knowledge of socket.io, I can't figure out how to log them in a div on my index.html file
i.e. I need the server.js to emit(?) the connections and disconnections and append them to the div instead of just logging them on my console.
I included my server.js file and my html file (which contains the client sided script).
My server.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
ID = socket.id;
console.log('client id - ' + socket.id + ' connected.');
socket.on('disconnect', function() {
console.log('client id - ' + socket.id + ' disconnected.')})
})
server.listen(80, '95.211.186.223', function () {
console.log("Listening on 80")
});
My index.html
<!doctype html>
<html lang="en">
<head></head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<script>
var socket = io.connect('http://95.211.186.223:80');
socket.on('connect', function(data) {
console.log('ID: ' + socket.id)
});
</script>
<div id="log"></div>
</body>
</html>

There are many ways to implement that. Just one of them:
On server:
io.on('connection', function (socket) {
ID = socket.id;
console.log('client id - ' + socket.id + ' connected.');
io.sockets.emit('connect_event', data);
})
io.on('disconnect', function() {
ID = socket.id;
console.log('client id - ' + socket.id + ' disconnected.');
io.sockets.emit('disconnect_event', data);
}
If you want to know how to emit a message to everyone see the relevant question.
On client:
function addText(eventType) {
var p = document.createElement('p');
p.innerHTML = 'ID: ' + socket.id + ' ' + eventType;
document.body.appendChild(p);
}
socket.on('connect_event', function(data) {
addText('connected')
});
socket.on('disconnect_event', function(data) {
addText('disconnected')
});

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

How to display data from socket io to html page list

So, my program gets data from udp server and i just want to display it in list in HTML page 1 by 1 when it updates.
In console it works, but how to do it on page?
I got this code
index.js
var dgram = require('dgram'),
server = dgram.createSocket('udp4'); //this server gets data from udp packet
var msg;
server.on('message', function (message, rinfo) {
msg = message.toString('ascii'); //udp packet data to string
console.log(msg);
});
server.on('listening', function () {
var address = server.address();
console.log('UDP Server listening ' + address.address + ':' + address.port);
});
server.bind(8007);
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket) {
var tm = setInterval(function() {
socket.emit('datafromserver', {'datafromserver': msg});
}, 500);
socket.on('disconnect', function() {
clearInterval(tm);
});
});
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
and html page
<!doctype html>
<html>
<head>
<title>Scoreboard</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
</style>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io.connect('http://192.168.1.162:3000/');
socket.on('#dataonscreen', function(data) {
$('#dataonscreen').html(data.datafromserver);
console.log(data.datafromserver);
});
</script>
<ul id="dataonscreen"></ul>
</body>
</html>
I can't understand why this isn't working and how to fix it.
Please help!
Your socket.io server emits datafromserver while your code listens for #dataonscreen
Change either so that they are the same value and your code should work. I'm not sure how you have console output since the event is not being listened for

using jQuery with socket.io

I am trying to use jQuery in my socket.io js (index.js) file.
Whenever I try to do
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="index.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));
});
socket.on('new user', function(data){
$('#newUserMessage').text(data);
});
</script>
I get this error in my console
GET http://localhost:3000/index.js
ReferenceError: $ is not defined
I'm not sure why this would happen?
But if I remove it I cant use jQuery's functions in index.js?
My index.js file
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var $usernameInput = $('.usernameInput');
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
socket.broadcast.emit('new user', 'New User Joined, Say Hi :D');
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
function setUsername () {
username = cleanInput($usernameInput.val().trim());
if (username) {
socket.emit('add user', username);
}
}
You are a little confused, you have your front end and you have your back end.
Your index.js is your back end, you run that using NodeJS and you don't try to use jQuery on your back end, there's no DOM to manipulate. Also you don't include index.js on your front end, that's back end code.
This is wrong:
var $usernameInput = $('.usernameInput');
You can't access your DOM to get that value you have to send it to the back end, with some kind of event like this:
Front end
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chatMessage', $('#m').val());
$('#m').val('');
return false;
});
socket.on('connect', function(){
socket.emit('setUser', $('.usernameInput').val().trim());
});
socket.on('chatMessage', function(msg){
$('#messages').append($('<li>').text(msg));
});
socket.on('newUser', function(data){
$('#newUserMessage').text(data);
});
</script>
Back end
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.broadcast.emit('newUser', 'New User Joined, Say Hi :D');
socket.on('setUser', function(username){
console.log(username); //here you have your user name
});
socket.on('chatMessage', function(msg){
io.emit('chatMessage', msg);
});
});
Here is My code for socket IO
<script>
var socket = io.connect('<?php echo $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . ":8000" ?>');
console.log("tests" + socket);
socket.on('connect', function () {
});
socket.on('call_admin_notification', function (data) {
getAdminNotification();
});
</script>

Pass data from HTTP to node.js to TCP?

I recently started using Socket.io, and node.js as a result, and I am kind of stuck. I do not even know if this is a practical solution for my application, but hopefully someone can help.
All I have here is a webpage with a checkbox, which reports it's status to the node console, and then when a TCP client connects, it receives the status as well.
I am wondering how I would go about making this event continuous, so that the TCP client constantly receives updates on the status of the checkbox.
If anyone has any idea, please let me know, and sorry for the long code...
Server Code:
var net = require('net');
var app = require('express')(); <!-- These are mandatory variables -->
var http = require('http').Server(app);
var io = require('socket.io')(http);
var HOST = 'localhost';
var PORT = 4040;
GLOBAL.MYVAR = "Hello world";
var server = net.createServer();
server.listen(PORT, HOST);
app.get('/', function(req, res){ <!-- This sends the html file -->
//send the index.html file for all requests
res.sendFile(__dirname + '/index.html');
});
http.listen(3001, function(){ <!-- Tells the HTTP server which port to use -->
console.log('listening for HTTP on *:3001'); <!-- Outputs text to the console -->
console.log('listening for TCP on port ' + PORT);
});
<!-- everything below this line are actual commands for the actual app -->
io.on('connection', function(socket) // Opens the socket
{
socket.on('checkbox1', function(msg){ // Creates an event
console.log(msg); // displays the message in the console
MYVAR = msg; // Sets the global variable to be the contents of the message recieved
});
});
server.on('connection', function(socket){ // Opens the socket for the TCP connection
socket.write(MYVAR);
}).listen(PORT, HOST);
Client code:
<!doctype html>
<html>
<head>
<title>Socket IO Test</title>
<form action="">
<input type='checkbox' onclick='checkbox1(this);'>Checkbox1</label>
</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();
var number = 0;
function checkbox1(cb) {
socket.emit('checkbox1', 'checkbox 1 = ' + cb.checked);
return false;
}
</script>
</body>
</html>
Cheers
I believe the issue here is that you don't have a way to reference the TCP socket. Once you do have a reference it is as easy as receiving a message and sending it.
This will work for a single client.
var net = require('net');
var app = require('express')(); <!-- These are mandatory variables -->
var http = require('http').Server(app);
var io = require('socket.io')(3000);
var s;
var HOST = 'localhost';
var PORT = 4040;
GLOBAL.MYVAR = "Hello world";
var server = net.createServer();
server.listen(PORT, HOST);
app.get('/', function(req, res){ <!-- This sends the html file -->
//send the index.html file for all requests
res.sendFile(__dirname + '/index.html');
});
http.listen(3001, function(){ <!-- Tells the HTTP server which port to use -->
console.log('listening for HTTP on *:3001'); <!-- Outputs text to the console -->
console.log('listening for TCP on port ' + PORT);
});
<!-- everything below this line are actual commands for the actual app -->
io.on('connection', function(socket) // Opens the socket
{
socket.on('checkbox1', function(msg){ // Creates an event
console.log(msg); // displays the message in the console
MYVAR = msg; // Sets the global variable to be the contents of the message recieved
s.write(MYVAR, 'utf-8');
});
});
server.on('connection', function(socket){ // Opens the socket for the TCP connection
s = socket;
s.write(MYVAR, 'utf-8');
}).listen(PORT, HOST);
This will work for multiple clients.
var net = require('net');
var app = require('express')(); <!-- These are mandatory variables -->
var http = require('http').Server(app);
var io = require('socket.io')(3000);
var sockets = [];
var HOST = 'localhost';
var PORT = 4040;
GLOBAL.MYVAR = "Hello world";
var server = net.createServer();
server.listen(PORT, HOST);
app.get('/', function(req, res){ <!-- This sends the html file -->
//send the index.html file for all requests
res.sendFile(__dirname + '/index.html');
});
http.listen(3001, function(){ <!-- Tells the HTTP server which port to use -->
console.log('listening for HTTP on *:3001'); <!-- Outputs text to the console -->
console.log('listening for TCP on port ' + PORT);
});
<!-- everything below this line are actual commands for the actual app -->
io.on('connection', function(socket) // Opens the socket
{
socket.on('checkbox1', function(msg){ // Creates an event
console.log(msg); // displays the message in the console
MYVAR = msg; // Sets the global variable to be the contents of the message recieved
for (var i = 0; i < sockets.length; i++) {
if(sockets[i]) {
sockets[i].write(MYVAR, 'utf-8');
}
}
});
});
server.on('connection', function(socket){ // Opens the socket for the TCP connection
sockets.push(socket);
socket.write(MYVAR, 'utf-8');
}).listen(PORT, HOST);

Running node.js on a website but not on localhost

I made an online multiplayer game. I works perfectly when I run it with node.js command prompt on localhost:3000. But when I try to run it on the website it is not doing what my app.js file says it to do. my questions are;
How can I make my node.js project run on my website rather than on localhost?
What will the port be instead of 3000?
Can I do this by uploading some file into my website via ftp?
Here is my app.js file
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
var usernumm = 0;
var usernum1 = [];
app.use(express.static(__dirname + '/public'));
server.listen(3000);
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket){
var endpoint = socket.manager.handshaken[socket.id].address;
console.log('***New connection from ' + endpoint.address + ':' + endpoint.port);
usernumm++;
io.sockets.emit('usernum', usernumm);
usernum1[usernumm] = endpoint.port;
console.log('usernum'+usernumm+'geldi'+findusernum());
socket.on('button1socket', function(){
io.sockets.emit('button1f', findusernum() );
console.log('user '+findusernum()+' pressed a button');
});
socket.on('buttonclickable', function(){
io.sockets.emit('buttonclickable1', findusernum() );
});
socket.on('disconnect', function () {
usernumm--;
io.sockets.emit('usernum', usernumm);
//sockets[usernum] = socket.port;
console.log('***Client disconnected');
});
//finds number of online users
function findusernum(){
for(var i = 0; i<9;i++){
if(usernum1[i] == endpoint.port){return i;}else{}
}
}
});
try:
var express = require('express');
var app = express();
var httpServer = require('http').Server(app);
var socketServer = require('socket.io')(httpServer);
var ip = 'iphere';
var port = 80;
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
socketServer.on('connection', function(socket){
console.log("A Client has connected.");
socket.on('disconnect', function(){
console.log("A Client has disconnected.");
});
});
httpServer.listen(port, ip, function(){
console.log("Listening to "+ip+":"+port);
});
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script type="text/javascript" src="http://ip:port/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket;
try{
socket = io("http://ip:port/", {'forceNew':true });
socket.on('connect', function(error){
if(error){
}
});
}catch(e){
}
</script>
</head>
<body>
</body>
</html>
after you have specified your ip and port
port forward the port you have specified to live your website/game using your router
then you can visit it with http://yourpublicip:port/
if its port 80 then visit the page without the port.

Categories

Resources