How to avoid socket id change with socket.io? - javascript

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?

Related

Socket is not defined + other errors

Server side code:
const http = require("http");
const host = 'localhost';
const port = 8000;
const { Server } = require("socket.io");
// creating the server and starting it on port 8000
const server = http.createServer();
server.listen(port, host, () => {
console.log(`Server is running on http://${host}:${port}`);
});
// making io object
const io = new Server(server);
// listening to connections to the server
io.on('connection', (socket) => {
console.log('a user connected');
});
// listening on port 8000
server.listen(8000, () => {
console.log('listening on *:8000');
});
// chat message coming to server
socket.on("details", (chatBundle) => {
console.log(chatBundle);
});
Client side code:
<!DOCTYPE html>
<html>
<body>
<h1>CHAT ROOM</h1>
<form onsubmit="return sendServer()">
<label for="name">Name:
<input id="name" name="name" type="text">
</label>
<label for="text">Message:
<input id="text" name="text" type="text">
</label>
<input type="submit" id="send" >
</form>
<script src="/Users/chanson/node_modules/socket.io/client-dist/socket.io.js">
</script>
<script>
function sendServer(){
var sender = document.getElementById("name");
var text = document.getElementById("text");
var tempArray = [sender, text]
socket.emit(chatmsg, tempArray)
};
</script>
</body>
</html>
Aim: to make a chat messenger that would work on same computer browsers + ports. e.g. Firefox port user can communicate to Chrome, Edge, Opera and Safari. (please don't ask why I have so many browsers).
Client side errors (3)
chatmsg has not been defined or given a value
socket has not been created or assigned to a variable
sendServer returns undefined, not false and hence will not prevent form submission when the submit button is pushed. (Calling event.preventDefault in the submit event is a more modern method of preventing submission).
A script element that addresses these considerations:
<script>
const chatmsg = "details"; // added
const socket = io(); // added
function sendServer(){
var sender = document.getElementById("name");
var text = document.getElementById("text");
var tempArray = [sender, text]
socket.emit(chatmsg, tempArray)
return false; // added
};
</script>
Server side errors (several)
No application.
The client page must be served from the server in order to communicate with it using sockets - CORS errors are generated if the client page is loaded using the file:// protocol and then tries to communicate with the local host server using socket.io.
A simple static express server can be set up to serve a request for http://localhost:8000/client.html.
The server must also be capable of serving the socket.io client script using a suitable url in the src attribute of the client side script tag. A client tag used in testing was
<script src="node_modules/socket.io-client/dist/socket.io.js"></script>
but will depend on server directory structure and possibly the version of socket.io.js in use.
The app is supplied as an argument when creating the http server.
In the version of socketIO used for testing, requiring socket.io returns a function that is called to generate a socket server. Check documentation to verify that later versions return an export object with a Socket property. (See notes at bottom of answer)
Socket message listening
This is in the wrong place - socket is an argument supplied to the io.on("connection", handler) handler function, and listening to socket events generated by the user who made the connection should be made in function scope of the connection handler.
Code used in testing
client.html
<!DOCTYPE html>
<html>
<body>
<h1>CHAT ROOM</h1>
<form onsubmit="return sendServer()">
<label for="name">Name:
<input id="name" name="name" type="text">
</label>
<label for="text">Message:
<input id="text" name="text" type="text">
</label>
<input type="submit" id="send" >
</form>
<!-- <script src="/Users/chanson/node_modules/socket.io/client-dist/socket.io.js"> -->
<!-- particular to server setup: -->
<script src="node_modules/socket.io-client/dist/socket.io.js"></script>
<script>
const chatmsg = "details";
var socket = io();
function sendServer(){
var sender = document.getElementById("name");
var text = document.getElementById("text");
var tempArray = [sender, text]
socket.emit(chatmsg, tempArray)
return false;
};
</script>
</body>
</html>
node script
const http = require("http");
const host = 'localhost';
const port = 8000;
//** const { Server } = require("socket.io");
//**
const express = require('express');
const app = express();
app.use(express.static('./'));
const socketIO = require("socket.io");
// creating the server and starting it on port 8000
//**const server = http.createServer();
const server = http.createServer(app);
server.listen(port, host, () => {
console.log(`Server is running on http://${host}:${port}`);
});
// making io object
//** const io = new Server(server);
const io = socketIO(server, {cookie: false}); /* prevent io cookie - see https://github.com/socketio/socket.io/issues/2276 */
// listening to connections to the server
io.on('connection', (socket) => {
console.log('a user connected');
//** move listening here, where socket is defined
// chat message coming to server
socket.on("details", (chatBundle) => {
console.log(chatBundle);
});
});
The version of socket.io used to prepare this answer was 2.2.0.
Version 4.x documentation confirms socket is still supplied to the connection handler.
Version 4.x doco shows Server as being imported from the socket.io package, which can't be done in CommonJS packages because the don't support the import statement.
AFAIK if in node you require an ECMA module package from within a CommonJS package, you are returned the default export of the ECMASScript module. You may need to investigate further if it is not the Server constructor function (or class object) exported in version 4.
You can import ECMAScript modules in CommonJS using the import function (not keyword), but the import operation is asynchronous. See How to use ES6 modules CommonJS for further details.
I don't like the way you import socket client please do something like
<script src="/socket.io/socket.io.js"></script>
or CDN
<script src="https://cdn.socket.io/4.5.4/socket.io.min.js" integrity="sha384-/KNQL8Nu5gCHLqwqfQjA689Hhoqgi2S84SNUxC3roTe4EhJ9AfLkp8QiQcU8AMzI" crossorigin="anonymous"></script>
after that, you have to instantiate tour socket like:
const socket = io();
const text = document.getElementById("text")
socket.emit('chatMessage', text.value);
Make sure the event name is string ex here: chatMessage

socket id is not showing on html client side

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.

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