Simple WebSocket Application with NodeJS

I am going to make a simple WebSocket application waiting for clients to connect. Clients will be Android users, and the application itself is a simple chat for two peoples. Therefore, for an Android application, I need to know the WebSocket address (starts with ws: // or wss: // ). I already have a site where I install nodejs. But after a couple of days I was completely stuck with what was happening and how to get something to work. I would even be glad to see that nodejs catches any WebSocket messages and that it is.

I read several tutorials about nodejs and socket.io , and again I have no idea where to get this ws: // address and make it work somehow.

For example, from the manual for socket.io , we have:

var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendfile('index.html'); }); io.on('connection', function(socket){ console.log('a user connected'); }); http.listen(3000, function(){ console.log('listening on *:3000'); }); 

Is this a simple web application already? Where is my desired ws: // address in this case? Maybe I just need to download this bunch of code on my server and send requests to ws: //mydomain.com: 3000 ?

+5
source share
1 answer

If you use the socket.io library on the server, then you need to use the socket.io library on the client, because it is a protocol on top of webSocket, so both ends must speak the same language.

webSockets (and socket.io in this case) are designed to share your web server. Thus, any request to connect to the WebSocket server is sent to the same host and port as your web server.

Each webSocket request starts with an HTTP request (thus it is processed by your web server) and this HTTP request as a header in it that asks for an upgrade to the webSocket protocol. When your web server sees this user header, it disables the management of the socket.io library, which then responds that the upgrade to the webSocket protocol is in order, and the socket that started working as an HTTP request now becomes a socket, the application says webSocket / socket .io.

The socket.io library automatically connects to your web server to view these protocol update requests.

On the web page, the socket.io client code for connecting to this would look like this:

 <script src="/socket.io/socket.io.js"></script> <script> var socket = io(); socket.on('connect', function() { // socket.io webSocket connection with your server is now established }); </script> 

The socket.io library will automatically connect to the same host from which the web page appeared. You do not even need to provide a URL.

+4
source

All Articles