CoffeeScript 双向客户端


本文整理自网络,侵删。

双向客户端

问题

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

解决方案

创建一个双向TCP客户机。

在 Node.js 中

net = require 'net'

domain = 'localhost'
port = 9001

ping = (socket, delay) ->
    console.log "Pinging server"
    socket.write "Ping"
    nextPing = -> ping(socket, delay)
    setTimeout nextPing, delay

connection = net.createConnection port, domain

connection.on 'connect', () ->
    console.log "Opened connection to #{domain}:#{port}"
    ping connection, 2000

connection.on 'data', (data) ->
    console.log "Received: #{data}"

connection.on 'end', (data) ->
    console.log "Connection closed"
    process.exit()

使用示例

可访问Bi-Directional Server:

$ coffee bi-directional-client.coffee
Opened connection to localhost:9001
Pinging server
Received: You have 0 peers on this server
Pinging server
Received: You have 0 peers on this server
Pinging server
Received: You have 1 peer on this server
[...]
Connection closed

讨论

这个特殊示例发起与服务器联系并在@connection.on 'connect'@处理程序中开启对话。大量的工作在一个真正的用户中,然而@connection.on 'data'@处理来自服务器的输出。@ping@函数递归是为了说明连续与服务器通信可能被真实的用户移除。

另请参阅Bi-Directional Server,Basic Client和Basic Server。

练习

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

标签:CoffeeScript

相关阅读 >>

CoffeeScript 计算(美国和加拿大的)感恩节日期

CoffeeScript 对象的链式调用

CoffeeScript 平方根倒数快速算法

CoffeeScript 将数组连接

CoffeeScript 计算复活节的日期

CoffeeScript 双向客户端

CoffeeScript 服务器

CoffeeScript 回调绑定

CoffeeScript 不使用 jquery 的 ajax 请求

CoffeeScript 服务端和客户端的代码重用

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




打赏

取消

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

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

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

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

评论

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