socket id is not showing on html client side - javascript

i am trying to get the socket id on the client side but for some reason it's not showing. Here is my code
client side
<html>
<head>
<meta charset="utf-8" />
<title>Ringneck</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">
<script src="https://www.WebRTC-Experiment.com/RecordRTC.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.4.1/socket.io.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io-stream/0.9.1/socket.io-stream.js"></script>
</head>
<body>
<div style="margin: 20px">
<h1 style="font-size: 18px;">Example 7: Media Translation Streaming</h1>
<div>
<button id="start-recording" disabled>Start Streaming</button>
<button id="stop-recording" disabled>Stop Streaming</button>
</div>
<h2 style="font-size: 16px; margin-bottom: 10px;">data.textTranslationResult.translation</h2>
<p>Record your voice in English, and see the German translation.</p>
<p>Keep recording for at least 4 seconds.</p>
<textarea id="results" style="width: 800px; height: 300px;"></textarea>
</div>
<script type="text/javascript">
const startRecording = document.getElementById('start-recording');
const stopRecording = document.getElementById('stop-recording');
let recordAudio;
const socketio = io();
console.log("JS file loaded"). // sanity check to make sure file is read
const socket = socketio.on('connect', function(msg) {
console.log("JS file loaded")
console.log("socket id: ",socket.id);
});
and my server side code
const express = require('express');
const cors = require('cors');
const path = require('path');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 3000;
app.use(cors());
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/public/index.html'));
});
function onConnection(socket){
console.log(`Client connected [id=${socket.id}]`);
var returndata = {
"test":"yes"
}
socket.emit('server_setup', `Server connected [id=${socket.id}]`);
}
io.on('connection', onConnection);
http.listen(port, () => console.log('listening on port ' + port));
my server console log is
Client is connected [id=_RMXhb8Vz9XgSqhGAAGa]
but I could not get any response on the client side. what am i missing and how can i fix this and get the socket id ?

When I run your code, I found that there was a client-side Javascript parsing error on this line:
console.log("JS file loaded").
because of the period. When I replace that period with a semi-colon like this:
console.log("JS file loaded");
I get this output on the server:
Client connected [id=eoxspnNtoTg-2Kj3AAAB]
and this output in the debug console of the browser:
JS file loaded
socket id: eoxspnNtoTg-2Kj3AAAB
If you're not already doing so, you should be looking in the browser console for errors.

Related

Not able to cross beyond my sql statement , the browser waits for something

I am new to node js and js, My code is not able to cross the SQL statement
here is my app.js snippet for the SQL statement
my app.js
//declaration
const bodyParser = require("body-parser")
const fs = require('fs')
const express = require('express')
const app = express()
var session = require('express-session');
const path = require('path')
app.use("/static", express.static('./static/'));
//For the body parser
app.use(bodyParser.urlencoded({extended: false}))
//parse the application Json
app.use(bodyParser.json())
// for the MySQL page
var mysql = require('mysql')
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'login'
})
app.get ('/todo',(req,res)=>{
res.writeHead(200,{'content-type' : 'text/html'})
fs.createReadStream('project1.html').pipe(res)
})
app.listen(process.env.PORT || 3000)
my todo.js
document.addEventListener('submit',myFunction)
function myFunction(e){
console.log("in the data post method")
let sql = 'INSERT INTO `acc` (`name`) VALUES (?)'
connection.query(sql,req.body.name,(error,result)=>{
if(error) throw error
console.log('value inserted')
connection.end();
})
e.preventDefault();
var text = document.querySelector("input").value;
var text = document.querySelector("input").value;
var node = document.createElement("p");
node.id="li1"
if (text!=""){
var textnode=document.createTextNode(text);
node.appendChild(textnode); //append the value to LI
text = document.getElementById("demo")
console.log(text) ;
document.getElementById("demo").appendChild(node); //append the value to UI
document.querySelector("input").value = ""
}
// document.getElementById("demo").addEventListener('mouseover',myFunction1)
str = document.getElementById("li1")
console.log(str)
}
//SELECTING AN ELEMENT THAT WAS CREATAED DYNAMICALLY AND APPLLY SOME PROPERTY
$(document).on('click','p',function(){
$(this).css({"text-decoration": "line-through",color : "pink" });
$(this).fadeOut(1500);
// $(this).remove();
})
my project1.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create a table</title>
<script src="./static/todo.js"></script>
</head>
<body>
<h1>ToDo</h1>
<form id="form" action="/data" method="post">
<input type="text" name = "name" class="input" id="tt">
</form>
<div id= "lip">
<ul id="demo" id="demo">
</ul>
</div>
</body>
</html>
I want to insert the user typed value in the database as well as I have to list them in the front end, both codes work separately but when I combine them, after executing the SQL statement the browser waits for something
Please help me.

How to avoid socket id change with socket.io?

I'm currently trying to make a support application (like, to live chat with support) and I'm looking for a way to avoid the change of the socket id.
Here is my index.js code:
const app = require('express')();
const http = require('http');
const server = http.createServer(app);
const io = require('socket.io')(server);
io.on('connection', function (socket) {
socket.on("hello",()=>{
socket.emit("hello",socket.id)
})
})
app.get("/",(req,res)=>{
res.sendFile(__dirname+"/client/index.html")
})
server.listen(1002)
And here is my client/index.html code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Socket.io</title>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<p id="socketid"></p>
<script>
const socket = io();
socket.emit("hello")
socket.on('hello',(message)=>{
document.getElementById("socketid").innerHTML=message;
})
</script>
</body>
</html>
Thanks in advance for your help!
I think you cannot make socketid constant. Every time you reconnect or connect a new socket id will be given to you. Actually why do you want to make socketid constant?

Socket.io and express ERR_CONNECTION_REFUSED error with Chat app

I'm following a tutorial about making a rock paper sissors game with a chat using socket.io and express. I'm only making the chat.
But I'm getting an error that the person in the tutorial isn't getting. I don't know how to fix it. I've search google but could only find very complicated solutions.
The error that I get when I try to send a message is 'ERR_CONNECTION_REFUSED'.
Here is my code:
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chat</title>
</head>
<body>
<div id="chatWrapper">
<ul id="chatUl"></ul>
</div>
<div class="buttons">
<form id="chatForm">
<input id="chat"/>
<button id="verstuur">Verstuur</button>
</form>
</div>
<script src="/socket.io/socket.io.js"></script>
<script src="client.js"></script>
</body>
</html>
Server.js
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const app = express();
const clientPath = `${__dirname}/../client`;
console.log(`Static van ${clientPath}`);
app.use(express.static(clientPath));
const server = http.createServer(app);
const io = socketio(server);
io.on('connection', (sock) => {
console.log("Iemand is verbonden");
sock.emit('message', "Hoi, je bent verbonden!");
sock.on('message', () => {
io.emit('message', text);
});
});
server.on('error', (err) => {
console.error("Server fout: " + err);
});
server.listen(8080, () => {
console.log('Chat opgestard op 8080');
});
Client.js
const writeEvent = (text) => {
// <ul> element
const parent = document.querySelector('#chatUl');
// <li> element
const el = document.createElement('li');
el.innerHTML = text;
parent.appendChild(el);
};
const onFormSubmitted = (e) => {
e.preventDefault();
const input = document.querySelector('#chat');
const text = input.value;
input.value = '';
sock.emit('message', text);
};
writeEvent('Welkom bij de chat!');
const sock = io();
sock.on('message', writeEvent);
document
.querySelector('#chatForm')
.addEventListener('submit', onFormSubmitted);
Any help?
ps. The tutorial that I am following: https://www.youtube.com/watch?reload=9&v=xVcVbCLmKew
And sorry for bad English
You just forgot the formal parameter of a function (server.js):
io.on('connection', (sock) => {
console.log("Iemand is verbonden");
sock.emit('message', "Hoi, je bent verbonden!");
sock.on('message', (/* variable here*/ text) => {
io.emit('message', text);
});
});
Also check the path to your files. Is "${__dirname}/../client" correct?

Render unicode text with wkhtmltoimage

Trying to use wkhtmltox to turn an HTML file to an image:
./server.js
const express = require('express');
const fs = require('fs');
const wkhtmltox = require('wkhtmltox');
const app = express();
const converter = new wkhtmltox();
app.get('/tagslegend.png', (request, response) => {
response.status(200).type('png');
converter.image(fs.createReadStream('tagslegend.html'), { format: "png" }).pipe(response);
});
var listener = app.listen(process.env.PORT, function () {
console.log('App listening on port ' + listener.address().port);
});
And ./tagslegend.html:
<!doctype html>
<html>
<body>
<dl>
<dt>中文</dt><dd>In mandarin language.</dd>
</dl>
</body>
</html>
I'm expecting back an image of the above HTML, e.g. (how my browser would render it):
Instead I get back this:
How can I render that HTML to a png dynamically with the correct chinese characters and serve it to clients?
Add
<meta charset="utf-8">
to the <head> of the HTML document

how to send an id="" to all socket in nodejs?

I have a problem with nodejs and socket.io
I tried in other discussions in order to understand how to solve my problem , but I did not succeed .
I'm going to create a board with score and I created a simple counter in javascript . I want to convey to all who open the ' localhost address : port with nodejs advances counter
this is what I have made ​​so far
tabellone.js
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http)
app.use(express.static(__dirname + '/public'));
io.emit('some event', { for: 'everyone' });
io.on('connection',function(socket){
socket.on('contatore', function(){
socket.broadcast.emit('contatore', contatore);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
index.html
<html>
<head>
<title>tab</title>
</head>
<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 src="/socket.io/socket.io.js"></script>
<body>
<ul id="tab"></ul>
<form id="form">
<p id="contatore">0</p>
<button id="m" type="button"
onClick="javascript:contatore_su();"> + </button>
<button type="button"
onClick="javascript:contatore_giu();"> - </button>
</form>
<script>
var s=0;
function contatore_su() {
s=s+1;
document.getElementById('contatore').innerHTML = s;
}
function contatore_giu() {
s=s-1;
document.getElementById('contatore').innerHTML = s;
}
</script>
<script>
var socket=io();
$('form').click(function(){
socket.emit('conteggio', $('#m').val());
$('#m').val('');
return false;
});
socket.on('conteggio', function(msg){
$('#tab').append($('<li>').test(msg));
});
</script>
</body>
</html>
I have previously created a chat by following what is written on socket.io but I can not convey to all connected sockets the advancement counter , thanks for the help
ps. Sorry for my english :')
Which is the code to trasmit the element, in this case that is
contatore
I do not know what to put in the
io.on('connection',function(socket){ //here what? });
I do not know how the insert of the fuction works

Categories