Categories: CoffeeScript 教程

CoffeeScript 双向服务器

双向服务器

问题

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

解决方案

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

练习

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

前端小白,在Web176教程网这个平台跟大家一起学习,加油!

Share
Published by
andy

Recent Posts

自定义指令:聊聊vue中的自定义指令应用法则

今天我们来聊聊vue中的自定义…

1 天 ago

聊聊Vue中@click.stop和@click.prevent

一起来学下聊聊Vue中@cli…

1 周 ago

Nginx 基本操作:启动、停止、重启命令。

我们来学习Nginx基础操作:…

2 周 ago

Vue3:手动清理keep-alive组件缓存的方法

Vue3中手动清理keep-a…

2 周 ago

聊聊React和Vue组件更新的实现及区别

React 和 Vue 都是当…

3 周 ago