Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple WebSocket application with NodeJS

I gonna to make a simple WebSocket application waiting the clients to connect to. The clients would be Android users, and the application itself is a simple chat for two peoples. So for the Android application I need to know WebSocket address (starts with ws:// or wss://). I already have some website, where I install nodejs. But after couple of days I completely stuck what's going on and how make something work. I would be even glad to see nodejs catches any WebSocket messages and that's it.

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

For example, from socket.io chat manual, 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 that already simple websocket application? Where is my desired ws:// address in that case? Maybe should I just upload that bunch of code on my server and send queries to ws://mydomain.com:3000 ?

like image 261
James May Avatar asked Sep 27 '22 23:09

James May


1 Answers

If you're using the socket.io library on the server, then you have to use a socket.io compatible library in the client too 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 built to share your webserver. So, any webSocket connect request to your server is just sent to the same host and port as your webserver.

Each webSocket request starts with an http request (thus it is handled by your web server) and that http request as a header in it that requests an upgrade to the webSocket protocol. When your web server sees that custom header, it passes off control to the socket.io library which then responds that the upgrade to the webSocket protocol is OK and the socket which started out life as an http request, now becomes the socket over which the app speaks webSocket/socket.io.

The socket.io library handles plugging into your web server automatically in order to see these protocol upgrade requests.

In the webpage, the socket.io client code to connect to this would just 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 back to the same host that the web page came from. You don't even need to put in an URL.

like image 184
jfriend00 Avatar answered Oct 12 '22 10:10

jfriend00