• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

CoffeeScript 双向客户端

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

双向客户端

问题

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

解决方案

创建一个双向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 ServerBasic ClientBasic Server

练习

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

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
CoffeeScript 双向服务器发布时间:2022-01-29
下一篇:
CoffeeScript 服务器发布时间:2022-01-29
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap