There is a nginx server on which the site is spinning. It took in one of the applications to use websockets. I installed NodeJS on the same server, added express, socket.io to it.

Directory structure:

/-папки -php файлы -папка socket.io -/static/js/node/server.js 

Server.js file

 var express = require('express'), http = require('http'), path = require('path'); var app = express(); var cookieParser = require('cookie-parser'); var server = app.listen(1337); var io = require('socket.io').listen(server); app.use(cookieParser); io.on('connection', function(client){ client.on('message', function(message){ console.log(message) }); client.on('disconnect', function(){ console.log('disconnected'); }); }); 

On the client

 <script src="/socket.io/socket.io.js"></script> <script> document.addEventListener('DOMContentLoaded', function(){ var socket = io.connect('xxxx',{port: 1337, 'transports': ['websocket','xhr-polling']}); }); </script> 

instead of xxxx - naturally real ip

At the output we get: alt text

And in the browser console: WebSocket connection to 'ws://xxxx/socket.io/?EIO=2&transport=websocket' failed: Error during WebSocket handshake: Unexpected response code: 200

If you do the connection like this:

 var socket = io.connect(); 

Then in the console it is clear, the transport goes polling at what several connections per second and in response we get the contents of the socket.io folder

Previously, I didn't deal with sockets and generally with nodejs, so this is somehow difficult for me. Can someone tell me where and what needs to be corrected?

alt text

    1 answer 1

    I have created a simple chat. The server.js server file is located in the root of the site, all others (index.html, client.js, style.css) are in the chat folder. Here is a snippet of code that is written in client.js:

     if (navigator.userAgent.toLowerCase().indexOf('chrome') != -1) { socket = io.connect('http://asana:8085', {'transports': ['xhr-polling']}); } else { socket = io.connect('http://asana:8085'); }` 

    So why in all browsers there is a connection with the server when accessing index.html, but in Chrome does not want? When I had all the files in the root of the site - everything was fine.

    In short, I solved this question: it is necessary for chrome to write:

     socket = io.connect('http://asana:8085', {'transports': ['websocket','xhr-polling']});