How to Use Sockets in JavaScript\Html

How to Use Sockets in JavaScript\HTML?

Specifications:

  • Web Sockets API

Articles:

  • HTML5 WebSocket and WebJneering

Tutorial:

  • HTML5 Rocks - WebSockets

Libraries:

  • Check this SO post html5 websocket
    need server?, it links to
    https://kaazing.com/download

How to use socket.io to communicate with front end?

To start with, this is incorrect:

require("socket.io")(http);

You need to pass your server there, not the http module and you need to assign the result to an io variable. So, after you've defined and initialized your server variable, you would do:

const io = require("socket.io")(server);

Now, io is a reference to your socket.io server instance on the server-side and it can be used to emit to all connected clients with io.emit(...).


Your client side error is likely because this <script> tag:

<script src ="/socket.io/socket.io.js"> </script>

is not working because your socket.io server was not initialized properly. It might sound counter-intuitive, but the socket.io server is what provides the response handler for the /socket.io/socket.io.js URL. When that is missing, it will cause io not to be defined in the client which will lead to the client-side error you report.


You may also want to reconsider trying to send the cpu usage value to the client 10 times per second. That's pretty frequent and with any decent number of clients, your server would be spending all of its time just sending data updates.

Trying to send a string message from javascript server to client using sockets; when pressing HTML button

I managed to solve this by using Websockets. Where my webserver acted as the client, and I adjusted my server.js to the following:

SERVER.JS

const WebSocket = require("ws");

const wss = new WebSocket.Server({ port: 9898 });

wss.on("connection", ws => {
console.log("New client connected!");

ws.on("message", data => {
console.log(`Client has sent us: ${data}`);

ws.send(data.toUpperCase());
});

ws.on("close", () => {
console.log("Client has disconnected!");
});

});

HTML

<!DOCTYPE HTML>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/assets/dcode.css">
<link rel="shortcut icon" href="/assets/favicon.ico" type="image/x-icon">
<title>WebSockets</title>
</head>

<body>

<script>
const ws = new WebSocket("ws://localhost:9898");

ws.addEventListener("open", () => {
console.log("We are connected!");

ws.send("Hey, how's it going?");
});

ws.addEventListener("message", ({ data }) => {
console.log(data);
});
</script>
</body>
</html>

HTML file can't connect to socketio

After dwelling in the lands of JavaScript for a long time, I found a solution to this issue which might be helpful to anyone who sees this post.

The solution to this issue was to change the version of socket.io I was using. I am unsure of what version the server was using in the example above. I tried running the same scripts again, but this time using the most up to date and compatible server and client versions of socket.io (v4.x). The sockets managed to connect, no matter the protocol (file:/// or http://).

Sample Image

This is in the socket.io docs here. If you want your sockets to connect, make sure the client and server versions are compatible. Because of this, I'm assuming that it was version incompatibility that was the issue when I created this post.

I hope that this post helps someone :D

How to keep socket.io client in frontend code

You can't have multiple servers listening on the same port. Run the servers on different ports and either:

  • Have a reverse proxy forwarding requests to your Socket.io server (which needs special handling) and your front end server or
  • Put an absolute URL in the script src and configure CORS.

Transfer data from nodejs to html using socket.io

This maybe solve your problem.

item.innerHTML = data.time

How to import socket.io from client-side in vanilla javascript?

You can do this:

Putting this in your index.html :

<body>  <script src="/socket.io/socket.io.js"></script>  <script src="main.js">  // some code here...</body>

Get data by socket.io in html page

I tested this locally. In your HTML file I made two changes and it worked.

1 - Replace io.connect('localhost', {port: 8080}); with io.connect('localhost:8080');

2 - There was a strange \u200b character at the end of the document.getElementById("date").innerHTML = "My new text!"; line. I deleted that and ended up with:

<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Get Data</title>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<div id="results"> This text will change </div>
<div id="date">sample another temp text</div>
<script>
// client code here
var socket = io.connect('localhost:8080');
socket.on('udp message', function(message) {
console.log(message)
document.getElementById("date").innerHTML = "My new text!";
});
socket.on('welcome', function(data) {
document.getElementById("results").innerHTML = data.message;
});
</script>
</body>
</html>

Which replaces the content of results.



Related Topics



Leave a reply



Submit