你想通过网络提供持续的服务,与客户保持持续的联系。
创建一个双向TCP服务器。
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
$ 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'@中 ,处理所有的输入端。真正的服务器可能会将数据传给另一个函数处理并生成任何响应以便源程序处理。
(c) 2024 chaojicainiao.com MIT license