CoffeeScript 双向服务器


本文整理自网络,侵删。

双向服务器

问题

你想通过网络提供持续的服务,与客户保持持续的联系。

解决方案

创建一个双向TCP服务器。

在 Node.js 中

net = require 'net'

domain = 'localhost'
port = 9001

server = net.createServer (socket) ->
    console.log "New connection from #{socket.remoteAddress}"

    socket.on 'data', (data) ->
        console.log "#{socket.remoteAddress} sent: #{data}"
        others = server.connections - 1
        socket.write "You have #{others} #{others == 1 and "peer" or "peers"} on this server"

console.log "Listening to #{domain}:#{port}"
server.listen port, domain

使用示例

可访问Bi-Directional Client:

$ coffee bi-directional-server.coffee
Listening to localhost:9001
New connection from 127.0.0.1
127.0.0.1 sent: Ping
127.0.0.1 sent: Ping
127.0.0.1 sent: Ping
[...]

讨论

大部分工作在@socket.on 'data'@中 ,处理所有的输入端。真正的服务器可能会将数据传给另一个函数处理并生成任何响应以便源程序处理。

练习

  • 为选定的目标域和基于命令行参数或配置文件的端口添加支持。

标签:CoffeeScript

相关阅读 >>

CoffeeScript 一个随机整数函数

CoffeeScript 策略模式

CoffeeScript 递归函数

CoffeeScript 单件模式

CoffeeScript 扩展内置对象

CoffeeScript 数学常数

CoffeeScript 检测与构建丢失的函数

CoffeeScript 使用 html 命名实体替换 html 标签

CoffeeScript 查找子字符串

CoffeeScript 回调绑定

更多相关阅读请进入《CoffeeScript》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...

    暂无评论...