简体   繁体   中英

Socket.io client without node.js

I would like to have a web page that connects (is a client) to socket.io/node.js backend, but the web page should not be provided through/started using node.js, but instead it should be a separate project without any node.js usage.

How can I do that?

Socket.io comes with two separate libraries, one for client usage and one for creating a server.
The client library can be used both in a web browser and also in a Node.js app.
The server library needs Node.js.

So it's important to implement your Socket.IO server with Node.js and then connect to it with the client library.

In order to use Socket.IO client library in a web page you should simply include it in the page using a script tag and then connect to your sever:

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost:8080');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>

Your HTML page can be provided using any technology you want; For example you can produce the HTML page using Django framework and Python as its backend. Or simply run a web server (eg Nginx) or even open the HTML page as a file in your browser of choice.

It is not expressly required to use node on the server side. As an example, Flask has as server-side library using python: https://flask-socketio.readthedocs.io/en/latest/

socket.io also has a C server library, and I am sure there are a number of other languages that can use it. The issue here is that all the node documentation uses the "/socket.io/socket.io.js"script URL which implies that node.js is supplying the file somehow but we would like to get that file to serve without using Node.

In the flask example, it looks like they serve it using this script tag:

<script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js" integrity="sha256-yr4fRk/GU1ehYJPAs8P4JlTgu0Hdsp4ZKrx8bDEDC3I=" crossorigin="anonymous"></script>

Depending on what your Server-side is using, they may have their own client-side implementation as well. I personally recommend reading the documentation for your socket.io implementation to see if they specify a client library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM