语法 类和对象 字符串 数组 日期和时间 数学 方法 元编程 jQuery Ajax 正则表达式 网络 设计模式 数据库 测试

发布于 2016-05-29 08:12:41 | 84 次阅读 | 评论: 0 | 来源: 网络整理

问题

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

解决方案

创建一个双向 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'@ 中 ,处理所有的输入端。真正的服务器可能会将数据传给另一个函数处理并生成任何响应以便源程序处理。

练习

  • 为选定的目标域和基于命令行参数或配置文件的端口添加支持。
最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务