课程表

CoffeeScript 语法

CoffeeScript 类和对象

CoffeeScript 字符串

CoffeeScript 数组

CoffeeScript 日期和时间

CoffeeScript 数学

CoffeeScript 方法

CoffeeScript 元编程

CoffeeScript jQuery

CoffeeScript 正则表达式

CoffeeScript 网络

CoffeeScript 设计模式

CoffeeScript 数据库

CoffeeScript 测试

工具箱
速查手册

CoffeeScript 双向客户端

当前位置:免费教程 » JS/JS库/框架 » CoffeeScript

问题

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

解决方案

创建一个双向 TCP 客户机。

在 Node.js 中

  1. net = require 'net'
  2. domain = 'localhost'
  3. port = 9001
  4. ping = (socket, delay) ->
  5. console.log "Pinging server"
  6. socket.write "Ping"
  7. nextPing = -> ping(socket, delay)
  8. setTimeout nextPing, delay
  9. connection = net.createConnection port, domain
  10. connection.on 'connect', () ->
  11. console.log "Opened connection to #{domain}:#{port}"
  12. ping connection, 2000
  13. connection.on 'data', (data) ->
  14. console.log "Received: #{data}"
  15. connection.on 'end', (data) ->
  16. console.log "Connection closed"
  17. process.exit()

使用示例

可访问 Bi-Directional Server

  1. $ coffee bi-directional-client.coffee
  2. Opened connection to localhost:9001
  3. Pinging server
  4. Received: You have 0 peers on this server
  5. Pinging server
  6. Received: You have 0 peers on this server
  7. Pinging server
  8. Received: You have 1 peer on this server
  9. [...]
  10. Connection closed

讨论

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

另请参阅 Bi-Directional ServerBasic ClientBasic Server

练习

  • 为选定的目标域和基于命令行参数或配置文件的端口添加支持。
转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号