0

On another terminal, $curl localhost:3001

However, on nodejs server side, I never saw "sdfsdf" for

console.log("sdfsdf");

Questions

1 Can some expert explain why?

2 How to fix it to make 'connect' callback triggered?

Thank you.

var express = require('express'),
http = require('http')

var app = express();
var server = http.createServer(app);
//var server = http.Server(app);

//server.listen(app.get('port'), function () {
server.listen(3001, function () {
    //logger.info('openHAB-cloud: express server listening on port ' + app.get('port'));
    console.log("3001");
});

app.get('/', function(req, res){
  //res.sendfile('index.html');
  res.send("xxx");
});

io = require('socket.io').listen(server);

io.on('connection', function(socket) {
    console.log("sdfsdf");
});
  • We would need to see the client code that is making a socket.io connection to see what may be wrong on that end. `io.on('connect', ...)` only gets triggered when a socket client connects to your server and in your specific case, it has to connect on port 3001. – jfriend00 Jun 30 '17 at 01:04
  • For the client side, I try 2 things 1 **$curl localhost:3001** 2 put **localhost:3001** in browser None of them I saw "sdfsdf". Do you mean I have done something wrong on the client side? Thank you. – user1384726 Jun 30 '17 at 01:14

2 Answers2

0

To connect to a socket.io server, you must use a socket.io client - you cannot just use a regular curl or http request.

A socket.io client must be specifically designed to connect to a socket.io server. That means it uses the socket.io message format on top of webSocket and it follows the proper convention that socket.io and webSocket use for connecting.

Here are some client-side examples: https://socket.io/docs/client-api/

The connection can be made either from browser Javascript with the appropriate socket.io library included or using any socket.io client-side library from some other Javascript environment.

To see a bit how webSocket connections (which socket.io uses), you may want to read this: How does WebSockets server architecture work?. And then, socket.io adds its own message layer on top of webSockets.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
0
const io = require('socket.io-client');

const socket = io('http://localhost:3001');
  • 2
    Some info on why you believe this extra code should be added, would be helpful to others looking for good quality answers. – Anthony Horne Jun 30 '17 at 12:34