首页 \ 问答 \ 导出Socket.io模块以在全球范围内可用。(Export Socket.io module to be available globally.)

导出Socket.io模块以在全球范围内可用。(Export Socket.io module to be available globally.)

好吧我有一些要求,我希望能够在我的服务器的任何地方使用Socket.IO,特别是在执行任何CRUD操作时发送事件的路径中。

以下是一个名为sockets.js的文件,我用它来初始化我的套接字。

(function IIFE() {
  2   'use strict';
  3
  4   var socketIO = require('socket.io');
  5
  6   exports.initialize = function (server) {
  7     var io = socketIO.listen(server)
  8
  9     io.sockets.on('connection', (socket) => {
 10       console.log(socket)
 11       console.log("Connected");
 12
 13       io.sockets.on('disconnect', (socket) => {
 14         console.log('Disconnect')
 15       });
 16     });
 17   }
 18
 19 })();

以下是我的app.js,它本质上是我的服务器。

    2 (function IIFE() {
    3   'use strict';
    4
    5   const chalk = require('chalk');
    6
    7   if(!process.env.NODE_ENV) {
    8     console.log(chalk.red('No environment specified...') + chalk.blue('defaulting to \'development\''));
    9     process.env.NODE_ENV = 'development';
   10   }
   11
   12   const express = require('express');
   13   const mongoose = require('mongoose');
   14
   15   const config = require('./config/environment');
   16
   17   mongoose.connect(config.mongo.uri, config.mongo.options);
   18
   19   mongoose.connection.on('error', function(err) {
   20     console.error('Mongo Error: ' + err);
   21   });
   22
   23   const app = express();
   24   const server = require('http').createServer(app);
   25
+  26   var io = require('./sockets.js');
+  27   io.initialize(server);
+  28
   29   require('./config/express')(app);
   30   require('./routes')(app);
   31
   32   server.listen(config.port, config.ip, function() {
   33     console.log('order-api listening on %d in %s mode', config.port, app.get('env'));
   34   });
   35
   36   exports = module.exports = app;
   37 })();

以下文件位于另一个名为api的文件夹中。 整个应用程序是一个功能正常的应用程序我试图将套接字集成到。 但是我似乎无法理解如何从我的sockets.js集成套接字并在以下路由处理程序中使用它们。

(function IIFE() {
  2   'use strict';
  3
  4   const router = require('express').Router();
  5
  6   router.use('/carts', require('./cart'));
  7   router.use('/orders', require('./order'));
  8   router.use('/reports', require('./report'));
  9   router.use('/validators', require('./validator'));
 10
 11   module.exports = router;
 12 })();

Ok So I have some requirements, I would like to be able to use Socket.IO anywhere throughout my server, specifically within the routes to send out events when any CRUD operations have been performed.

The following is a file named sockets.js which I am using to initialize my sockets.

(function IIFE() {
  2   'use strict';
  3
  4   var socketIO = require('socket.io');
  5
  6   exports.initialize = function (server) {
  7     var io = socketIO.listen(server)
  8
  9     io.sockets.on('connection', (socket) => {
 10       console.log(socket)
 11       console.log("Connected");
 12
 13       io.sockets.on('disconnect', (socket) => {
 14         console.log('Disconnect')
 15       });
 16     });
 17   }
 18
 19 })();

The following is my app.js which is essentially my server.

    2 (function IIFE() {
    3   'use strict';
    4
    5   const chalk = require('chalk');
    6
    7   if(!process.env.NODE_ENV) {
    8     console.log(chalk.red('No environment specified...') + chalk.blue('defaulting to \'development\''));
    9     process.env.NODE_ENV = 'development';
   10   }
   11
   12   const express = require('express');
   13   const mongoose = require('mongoose');
   14
   15   const config = require('./config/environment');
   16
   17   mongoose.connect(config.mongo.uri, config.mongo.options);
   18
   19   mongoose.connection.on('error', function(err) {
   20     console.error('Mongo Error: ' + err);
   21   });
   22
   23   const app = express();
   24   const server = require('http').createServer(app);
   25
+  26   var io = require('./sockets.js');
+  27   io.initialize(server);
+  28
   29   require('./config/express')(app);
   30   require('./routes')(app);
   31
   32   server.listen(config.port, config.ip, function() {
   33     console.log('order-api listening on %d in %s mode', config.port, app.get('env'));
   34   });
   35
   36   exports = module.exports = app;
   37 })();

The following file is in another folder called api. The entire application is a functioning application I am trying to integrate sockets into. However I cannot seem to understand how to Integrate sockets from my sockets.js and use them in the following route handlers.

(function IIFE() {
  2   'use strict';
  3
  4   const router = require('express').Router();
  5
  6   router.use('/carts', require('./cart'));
  7   router.use('/orders', require('./order'));
  8   router.use('/reports', require('./report'));
  9   router.use('/validators', require('./validator'));
 10
 11   module.exports = router;
 12 })();

原文:https://stackoverflow.com/questions/42237632
更新时间:2024-02-10 06:02

最满意答案

我找到了问题的答案,感谢@MigratedPigeon,因为他让我想到了默认servlet的类。

tomcat服务器有一个默认的servlet,tomcats的默认servlet类是

org.apache.catalina.servlets.DefaultServlet

另一方面,Websphere没有默认的servlet,这就是我收到错误“无法找到Servlet名称”的原因。

在我在原始问题中链接的答案中,静态文件服务可以通过使用web-ext.xml文件由websphere激活,但仍然无法解决我的web.xml文件具有“默认”servlet的问题。

在我们的应用程序中,我们使用spring,所以最后我用spring dispatcher servlet替换了web.xml中的默认servlet,现在我的web.xml文件对tomcat和websphere都有效。


I found the answer to my problem, thanks to @MigratedPigeon because he got me thinking about the class of my default servlet.

A tomcat server has a default servlet, the class for tomcats default servlet is

org.apache.catalina.servlets.DefaultServlet

Websphere on the other hand does not have a default servlet, thats why I get the error "Servlet Name could not be found".

As in the answer I linked in the original question, static file serving can be activated by websphere by using the web-ext.xml file but that still did not solve the issue of my web.xml file having a "default" servlet.

In our application we use spring, so in the end I replaced the default servlet in web.xml with springs dispatcher servlet and now my web.xml file is valid for both, tomcat and websphere.

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)