简体   繁体   English

Angularjs 中的 Socket.io

[英]Socket.io in Angularjs

I'm going to add some websockets capabilities in my Angular/nodejs application using socket.io.我将使用 socket.io 在我的 Angular/nodejs 应用程序中添加一些 websockets 功能。

The final purpose is to keep on server a "live" array of unavailable for writing documents (because someone else is editing them) .最终目的是在服务器保留一个不可用于编写文档的“实时”数组(因为其他人正在编辑它们) But I started from the socket.io chat example and I've got stuck very soon.但是我从 socket.io 聊天示例开始,很快就卡住了。 I'm sure I'm missing something trivial here.我确定我在这里遗漏了一些微不足道的东西。 $scope.sendMessage() doesn't emits anything.. $scope.sendMessage()不发出任何东西..

FRONT前部

html html

 <input type="text" class="form-control" placeholder="message" name="message" ng-model="message"> <button type="button" ng-click="sendMessage()"> sendMessage </button>

socket.io is wrapped in a service socket.io 被包装在一个服务中

app.factory('socket', function ($rootScope) {
    var socket = io.connect();
    return {
        on: function (eventName, callback) {
            socket.on(eventName, function () {
                var args = arguments;
                $rootScope.$apply(function () {
                    callback.apply(socket, args);
                });
            });
        },
        emit: function (eventName, data, callback) {
            socket.emit(eventName, data, function () {
                var args = arguments;
                $rootScope.$apply(function () {
                    if (callback) {
                        callback.apply(socket, args);
                    }
                });
            })
        }
    };
});

controller控制器

$scope.messages=[]
socket.on('init', function (data) {
});
socket.on('send:message', function (message) {
    console.log("send:message")
    $scope.messages.push(message);
});
$scope.sendMessage = function () {
    console.log("send:message")
    socket.emit('send:message',$scope.message);
    $scope.messages.push($scope.message);
};

SERVER服务器

var http = require('http');
var server = http.createServer(app);
var io = require('socket.io')(server);
io.on('connection', function (socket) {
  console.log('a user connected');
  socket.on('disconnect', function () {
    console.log('user disconnected');
  });

  socket.on('send:message', function (message) {
    console.log('send:message:'+message);
    socket.broadcast.emit('send:message', {
      text:message
    });
  });
});

I've created a little app using this stack.我使用这个堆栈创建了一个小应用程序。 Check out my project here .在这里查看我的项目。 I've used this wrapper around socket-io made for AngularJs and found it to be quite easy to use!我在为 AngularJs 制作的 socket-io 周围使用了这个包装器,发现它非常易于使用!

In essence, in my project I have the following:本质上,在我的项目中,我有以下内容:

NodeJs Server code (entry point): NodeJs 服务器代码(入口点):

class Server {
    constructor() {
        this.express = require('express');
        this.redis = require('redis');
        this.client = this.redis.createClient(); //creates a new client
        this.app = this.express();
        this.server = require('http').Server(this.app);
        this.io = require('socket.io').listen(this.server);
        this.app.use('/node_modules', this.express.static(__dirname + '/node_modules'));
        this.app.use('/static', this.express.static(__dirname + '/static'));
        this.app.get('/', (req, res) => {
            res.sendFile(__dirname+'/index.html');
        });

        this.server.listen(8081, '0.0.0.0', () => { // Listens to port 80
            console.log('Listening on ' + this.server.address().port);
        });
        this.setup();
    }

    setup() {
        this.io.on("connection", (socket) => {
            this.socket = socket;
            this.centralServer();
        });
    }
    ...
    ...
}

And then, in index.html , I've loaded the JS for the required libraries: 然后,在index.html ,我为所需的库加载了 JS:

<html lang="en">
<head>
   ...
   ...
    <script src="/node_modules/socket.io-client/dist/socket.io.js" type="text/javascript"></script>
    <script src="/node_modules/redis/index.js" type="text/javascript"></script>
    <script src="/node_modules/angular-socket-io/socket.min.js" type="text/javascript"></script>
    <script src="/static/js/main.js" type="text/javascript"></script>
    ...
    ...
</head>
<body ng-app="app">
    <div ng-include='"static/views/<mainDOM>.html"'></div>
</body>

And finally, in my Angular app , I've got the following: 最后,在我的 Angular 应用程序中,我有以下内容:

var app = angular.module("app", ['btford.socket-io']);
app.controller('myGame', ['$scope', 'socketFactory', function($scope, socketFactory) {
    class Player {
        constructor() {
            this.dom          = $scope;
            this.dom.Room     = {};
            this.socket       = socketFactory();
            this.dom.roomExists   = false;
            this.setup();
        }
    ...
    ...
    }
    $scope.player = new Player();
}

I think I've done a good job in this project of providing a minimal example of AngularJS + Socket-io.我认为我在这个项目中做得很好,提供了一个 AngularJS + Socket-io 的最小示例。

This is indeed a complex problem you have created for yourself.这确实是你为自己创造的一个复杂问题。 I would do it by creating a backend service (over http) to manage the locking.我会通过创建一个后端服务(通过 http)来管理锁定。

When a user asks to edit a document, they are granted a lock, and and can enter the edit page.当用户要求编辑文档时,他们被授予锁定,并且可以进入编辑页面。 When they save it, the lock is released.当他们保存它时,锁被释放。 If another user asks to edit, the status return tells them it is locked, and they are shown an error dialog.如果另一个用户要求编辑,状态返回告诉他们它被锁定,并显示一个错误对话框。

You may need to have some kind of timeout on the locks in case the user closes the browser, or forgets to save.如果用户关闭浏览器或忘记保存,您可能需要在锁定上设置某种超时。 Managing this over socket connections will be a lot of work, and difficult to debug.通过套接字连接管理这个将需要大量工作,并且难以调试。 keeping everything as simple http requests will be much easier.将所有内容保持为简单的 http 请求会容易得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM