CoffeeScript 雙向客戶端

2022-06-29 17:13 更新

雙向客戶端

問(wèn)題

你想通過(guò)網(wǎng)絡(luò)提供持續(xù)的服務(wù),與客戶保持持續(xù)的聯(lián)系。

解決方案

創(chuàng)建一個(gè)雙向TCP客戶機(jī)。

在 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()

使用示例

可訪問(wèn)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

討論

這個(gè)特殊示例發(fā)起與服務(wù)器聯(lián)系并在@connection.on 'connect'@處理程序中開(kāi)啟對(duì)話。大量的工作在一個(gè)真正的用戶中,然而@connection.on 'data'@處理來(lái)自服務(wù)器的輸出。@ping@函數(shù)遞歸是為了說(shuō)明連續(xù)與服務(wù)器通信可能被真實(shí)的用戶移除。

另請(qǐng)參閱Bi-Directional Server,Basic ClientBasic Server。

練習(xí)

  • 為選定的目標(biāo)域和基于命令行參數(shù)或配置文件的端口添加支持。
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)