I have a minimalist socket.io with running on Node.js with a HTML client.
This is my minimalist server code (server.js):
const io = require('socket.io')(3000);
io.on('connection', (socket) => {
console.log(`new connection : ${socket.id}`);
});
and my minimalist client code (client.html):
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.1.3/socket.io.js"></script>
<script>
var socket = io('http://localhost:3000/');
</script>
<title>Document</title>
</head>
<body>
</body>
</html>
When I open client.html I get the message:
new connection : DedBsiEyAHLIu86oAAB0
which is fine, however after 7-8 seconds I get other new connection messages with differents socket ID :
new connection : K3DUMN7SJ0tOU7TsAACO
new connection : 3kCOVCz9fwRWtIypAACP
new connection : HgMVgpeP7raq1c4YAACQ
new connection : U6-lD-3lT1vT39_oAACR
new connection : aQCKYpBUVXD7t8WIAACS
On Chrome devtools-network tab, the same repeating message is displayed (which populate the new connection) :
Request URL: http://localhost:3000/socket.io/?EIO=4&transport=polling&t=NYCWok4
Request Method: GET
Status Code: 200 OK
Remote Address: [::1]:3000
Referrer Policy: strict-origin-when-cross-origin
Your help is greatly appreciated.
Regards
Pierre.
I realized that I was using a CORS enable plug-in with Chrome, I disable it which solve my problem
Related
tl;dr: Chrome is not sending "If-None-Match" header for HTTPS request but sends it for HTTP request. Firefox always send "If-None-Match", both in HTTPS and HTTP.
I was trying to optimize cookies management for my node server when I came across a weird behavior with Chrome. I will try to describe it and compare it with Firefox.
First, here is the HTTP node server I'm using to test this:
#!/usr/bin/env node
'use strict';
const express = require('express');
const cors = require('cors');
const compression = require('compression');
const pathUtils = require('path');
const fs = require('fs');
const http = require('http');
let app = express();
app.disable('x-powered-by');
app.use(function (req, res, next) {
res.set('Cache-control', 'no-cache');
console.log(req.headers);
next();
});
app.use(express.json({ limit: '50mb' }));
app.use(cors());
app.use(compression({}));
let server = http.createServer(app);
app.get('/api/test', (req, res) => {
res.status(200).send(fs.readFileSync(pathUtils.join(__dirname, 'dummy.txt')));
});
server.listen(1234);
And there the client code :
<!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>Document</title>
</head>
<body>
<script>
let test = fetch('http://localhost:1234/api/test', { mode: 'no-cors' })
.then((res) => {
return res.text();
})
.then((resText) => console.log(resText));
</script>
</body>
</html>
I use the header "no-cache" to force the client to re-validate the response.
If I've understood correctly how the cache work, I'm expecting client to send the request with the "If-None-Match" header having the previous request's e-tag and the server responding with a 304 code.
Here is the result when I refresh the page in Firefox (so at least one response has already be received). I embedded the server log of the request header.
Here the header "If-None-Match" is sent by the client request, as expected.
Now the same test with Chrome gives :
Well, here Chrome shows a 200 response code, but under the hood, it's really a 304 response that is sent by the server, which is shown by this wireshark capture :
As you can see, Chrome send the "If-None-Match" header with the correct e-tag, hence the 304 response.
So now, let's try this with HTTPS. In the server code, I just replaced require('http'); by require('https') and pass my ssl keys in createServer options (as described here)
So first, Firefox behaviour:
I've included the wireshark capture. And as you can see, everything is right, Firefox has the expected behaviour.
Now let's see the same thing with Chrome :
Here is my problem : as you can see, "If-None-Match" is not sent by Chrome. So as expected, the server returns a 200 response which can be seen in the wireshark capture (I refreshed the page twice, that's why there are 2 exchanges).
Do anyone have an idea on why Chrome has this weird behaviour?
I think it happened because you didn't set in your setting the certificat of your localhost.
Go to the settings and add it :)
chrome settings capture
I trained a custom object detection model using Google Cloud AutoML and exported the model as a TensorflowJS package.
However, when I try running the model using the HTML deployment example they have here https://cloud.google.com/vision/automl/object-detection/docs/tensorflow-js-tutorial?hl=en_US, it does not seem to work.
My tensorflowjs package from the export (model.json, dict.txt, group1-shard1of3,group1-shard2of3, group1-shard3of3)
are in the same directory as the index.html. I also have an index2.html. In index.html I use the same
imports for tfjs and tfjs-automl as the example here. In the index2.html I use CDN sources for tfjs and tfjs-automl.
The create web app example I followed is : https://github.com/tensorflow/tfjs/blob/master/tfjs-automl/code_snippets/object_detection.html
My repo with my custom object detection model is: https://github.com/mmmwembe/automl-tensorflowjs.git including the tensorflowjs model package and the test-images.
My Index.html file is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cards AutoML Model - TensorflowJS</title>
</head>
<body>
<script src="https://unpkg.com/#tensorflow/tfjs"></script>
<script src="https://unpkg.com/#tensorflow/tfjs-automl"></script>
<img id="test-image" src="test-images/test-image-01.jpg">
<script>
async function run() {
const model = await tf.automl.loadObjectDetection('model.json');
const img = document.getElementById('test-image');
const options = {score: 0.5, iou: 0.5, topk: 20};
const predictions = await model.detect(img, options);
// [END load_and_run_model]
console.log(predictions);
// Show the resulting object on the page.
const pre = document.createElement('pre');
pre.textContent = JSON.stringify(predictions, null, 2);
document.body.append(pre);
}
run();
</script>
</body>
</html>
What am I missing here?...I've run this with Chrome browser using Live Server in vscode editor as well as with nodejs using http-server -p 8000
I've been trying to learn how to set up a node.js server for a simple website for the first time and am encountering some strange behavior. When I open my index.html file from my computer it opens up perfectly with all of the CSS working properly. However I then set up a basic node.js server and when accessing the index.html file through my browser it only loads the html but not the CSS.
I'm extremely new to this so haven't been able to try much, also because the code is extremely simple so can't see what's missing (I tried following this tutorial if that helps). I also found another question that seemed similar on here but it didn't have an answer and didn't really help, I did check that all the files are UTF-8.
The HTML:
<html>
<head>
<title>My Page</title>
<link rel="stylesheet" href="styles.css" type="text/css">
</head>
<body>
<h1>A headline</h1>
</body>
</html>
And the node.js server:
const http = require("http");
const fs = require("fs");
const server = http.createServer((req, res) => {
res.writeHead(200, {"Content-Type": "text/html"});
const myReadStream = fs.createReadStream(__dirname + "/index.html", "utf8");
myReadStream.pipe(res);
});
server.listen(3000, "127.0.0.1");
console.log("Listening to port 3000");
When I include the CSS within <style> tags and directly in index.html it does work, but I've tried putting <link rel="stylesheet" href="styles.css" type="text/css"> between <style> tags and that still doesn't (it would also be weird if that's necessary seeing as it displays perfectly when I simply open the html file). I've also tried removing type=text/css but that didn't seem to change anything. Any help would be much appreciated!
You need to serve the style.css as well. You are serving the index.html but in the index.html it is hitting http://127.0.0.1:300/style.css when the request is coming to your app it is STILL serving the index.html file. (You can confirm this in Network pane of developer tools)
const server = http.createServer(function (req, res) {
const url = req.url;
if (url === '/style.css') {
res.writeHead(200, { 'Content-Type': 'text/css' }); // http header
fs.createReadStream(__dirname + "/style.css", "utf8").pipe(res);
} else {
res.writeHead(200, { 'Content-Type': 'text/html' }); // http header
fs.createReadStream(__dirname + "/index.html", "utf8").pipe(res);
}
})
Note: It is very easy to achieve this using express, probably the most popular nodejs package.
I'm trying to play around with sockets. I created a web server in node:
var http = require("http");
var server = http.createServer(function(req,res){
console.log("server has been created");
res.writeHead(200,{"Content-type:": "text/plain"});
res.end("Welcome to my supa' nodejs app");
}).listen(1337);
console.log("Server running at 127.0.0.1:1337");
var io = require("socket.io").listen(server);
io.sockets.on("connection", function(socket){
socket.on("input_written",function(){
console.log("someone clicked the button");
});
});
I also have a html file:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html lang="en">
<head>
<title>Home page</title>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect("http://localhost:1337");
function clickedButton()
{
socket.on("connect",function(){
socket.emit("input_written");
});
}
</script>
<button type="button" onclick="clickedButton()">Click me</button>
</body>
</html>
What I'm trying to achieve is when I press that button my console logs "someone clicked the button". However at the moment nothing happens. I'm not sure what I'm missing
UPDATE
As #Zub recommended I added
console.log("clicked");
right before the socket.emit();
I checked the console and this is the output:
Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost/socket.io/socket.io.js
Uncaught ReferenceError: io is not defined (index):11
Uncaught TypeError: Cannot call method 'on' of undefined
Since you bind node server on 1337, you have to point that port when you load socket.io.js script.
So try to replace
<script src="/socket.io/socket.io.js"></script>
with
<script src="http://localhost:1337/socket.io/socket.io.js"></script>
Edit
You should also initialize client socket.io connection beyond clickedButton function and leave just socket.emit("input_written"); in it.
The url in your browser needs to match the socket connection url. You have localhost in your io.connect, so make sure the url in your browser reads http://localhost/. If you connect to http://127.0.0.1/ in your browser then it won't work.
I suppose I'm havin' a beginner's problem regarding websocket connection.
Here's the thing, I'm researching on using websocket and I followed this code:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function WebSocketTest()
{
if ("WebSocket" in window)
{
alert("WebSocket is supported by your Browser!");
// Let us open a web socket
var ws = new WebSocket("ws://172.16.0.195:8080/echo");
ws.onopen = function()
{
// Web Socket is connected, send data using send()
ws.send("Message to send");
alert("Message is sent...");
};
ws.onmessage = function (evt)
{
var received_msg = evt.data;
alert("Message is received...");
};
ws.onclose = function()
{
// websocket is closed.
alert("Connection is closed...");
};
}
else
{
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}
}
</script>
</head>
<body>
<div id="sse">
Run WebSocket
</div>
</body>
</html>
... which I copied from the internet. When I tested it, Firefox said that my browser supports websocket feature but it DOESN'T ESTABLISH CONNECTION TO MY SERVER. I try to telnet our server in port 80 and I could gain connection to it. But if I am to use websocket connection in my page,it does not establish connection anymore.
Thank you very much in advance for any inputs/help.
[EDIT]
** by the way, does ".../echo" in my specified websocket connection has to do something with it? I mean, do I have to have some echo.php in my server?
This tutorial helped me a lot:
Getting started with HTML5′s Web Sockets
Now I have my server set up already.