Node + AngularJs + Socket.io:net :: ERR_CONNECTION_REFUSED

时间:2016-03-29 18:44:29

标签: angularjs node.js socket.io digital-ocean socket.io-1.0

我一直在我的浏览器控制台中收到此错误,因此我认为这是一个angular + socket.io问题:

GET http://localhost:3000/socket.io/?EIO=3&transport=polling&t=LF3gkk7 net::ERR_CONNECTION_REFUSED

Eventho我遵循了告知更改角度变量io的建议,如:

ctrl.socketIo = io();
ctrl.socketIo = io.connect();
ctrl.socketIo = io.connect('http://localhost:3001');

没有一个有效!

这是我的Angular控制器的外观:

angular.module("app")
    .controller("chatController", [
        'userService',
        function (userService) {

            var ctrl = this;
            ctrl.messages = [];

            ctrl.socketIo = io();
            ctrl.userName = userService.name;

            ctrl.submit = function () {

               ctrl.socketIo.emit("chat_message", ctrl.inputMessage);

               ctrl.messages.push(ctrl.inputMessage);           

               ctrl.inputMessage = null;
            };


            ctrl.socketIo.on("update_clients", function (msg) {

                ctrl.messages.push(msg);

            });

         }]
     );

我的index.html路径指向dirs:

<!doctype html>
<html>
<head>
 //boilerplate...
</head>

<body ng-app="app">

 //boilerplate...

   <script src="/bower_components/socket.io-client/socket.io.js"></script>

//boilerplate...

</body>
</html>

正如您在我的目录结构中看到的那样,路径正确指向了socket.io.js:

enter image description here

更新

我正在使用Digital ocean VPS,当我运行netstat -a -p时,似乎没有使用PORT 3000.

UPdate 2:

我的应用中的一项服务是尝试连接到localhost:3000所以我删除了那部分因为我现在不需要套接字我现在得到了:

enter image description here

更新3后端代码:

'use strict';

var express = require("express");
var app = express();
var http = require("http");
var server = http.createServer(app);
var io = require("socket.io")(http);

//use environment var PORT or 3001
var portNum = 3001;


//route handler
app.get("/", function (req, res) {

    res.sendFile("./index.html", {root: "./client/"});
});

app.use(express.static('./client'));

io.on("connection", function (socket) {

    socket.on("chat_message", function (msg) {

        socket.broadcast.emit('update_clients', msg);

    });
});


server.listen(portNum, function () {
    console.log("listening on port: " + portNum);
});

1 个答案:

答案 0 :(得分:1)

您收到404,因为您的socket.io模块未正确初始化 请尝试以下代码。

'use strict';

var express = require("express");
var app = express(); 
var http = require("http").Server(app);
var io = require("socket.io")(http);

//use environment var PORT or 3001
var portNum = 3001;


//route handler
app.get("/", function (req, res) {
   res.sendFile("./index.html", {root: "./client/"});
});

app.use(express.static('./client'));

io.on("connection", function (socket) {
   socket.on("chat_message", function (msg) {
      socket.broadcast.emit('update_clients', msg);
   });
});


http.listen(portNum, function () {
   console.log("listening on port: " + portNum);
});