node.js - 在 node js 中构建可扩展的 tcp 服务器

标签 node.js design-patterns tcp dependency-injection

所以我不确定我的标题是否最准确,但我尽力给出了最好的解释。

我最近在一次工作面试中被问到这个问题(或多或少,因为我不记得完整的问题。这是我的头脑):

You need to make a simple tcp server that can be accessed through puTTy (or any other client for that matter).

Once you are in, you need to write:

login < username > (Doesn't matter what username).

once you are logged in you have 3 operations you can do:

  • showDevices - will return a list of devices (Currently we have lamp and an airconditioner) - we can write mock objects. Let's assume they have a number Id.

  • Switch < deviceId > < on|off > - sets the device on or off.

  • SetValue < deviceId > < double > - set's the device's ranged value (Air condition tempature)

Important things:

  • Separation - Separate the logic and communication layer. We work with a telenat server now but we will want to switch to an http server in the future. The process should be easy.

  • Extensibility- We currently have 4 operations (login, showDevices, Switch, SetValue) - write the server so it would be very easy for other programmers to add another operation. The code should be self-explanatory

作业可以用任何语言编写。我尝试用 C# 编写它,直到我被卡住而无法继续。最近我更喜欢 Node js 并决定再试一次...所以我想请你们为这个解决方案提供一些有用的指导。

  • 如何最好地分离通信层和逻辑层?

  • 我应该实现某种设计模式以便更轻松地添加命令吗? (我查看了命令设计模式,但无法确定它是否适用于这种情况)

  • 任何能真正引导我走上正确轨道(无需告诉我确切做什么)的东西都将不胜感激。

谢谢!

最佳答案

我真的很喜欢这个挑战,我可能要偷用它来进行我自己的技术面试。 :)

我认为(因为你让我不要深入研究编写代码),我在 Node 中处理它的方式类似于 commander.js 模块。

因此,一个处理套接字的模块,可能只是一个允许连接的 server.js 文件,然后需要公开可用命令的模块。

可用的命令只是(取决于您希望如何允许升级)给定目录中的所有模块(如 commander.js 那样)或所有以特定关键字为前缀的模块(如 grunt 那样)。

如果您不想自己做,您可以使用 require-directory 模块要求目录中的所有文件,然后通过数组访问符号访问每个命令。

如果级别太高请告诉我,但这是我在 Node.js 中采用的一般方法。

在 C# 中会有点困难,您需要依靠反射来允许在运行时添加新插件,或者使用 DI 容器在编译时查找它们。

关于node.js - 在 node js 中构建可扩展的 tcp 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37141539/

相关文章:

node.js - TypeScript 中 `import from` 和 `import require` 之间的区别

sql - 尝试从 Node.js 创建 SQL 数据库连接时出现连接错误

java - BO 和服务之间的区别?

java - 使用设计模式时,您可以在多大程度上防止修改现有代码?

tcp - 为什么使用 AT 命令从 Arduino GPRS 连接到 xively 时 TCP 连接一直关闭?

C++ 服务器/客户端回显某些输入末尾附加的奇怪字符

javascript - 如何在 docuSign 中签名完成后重定向到后面

node.js - 为什么测试时我的 cookie 在我的处理函数中不可用?

user-interface - 您知道 GUI 编程的任何模式吗? (不是设计 GUI 的模式)

c - 通过 TCP 填充数据