EventMachine 系列之简单的服务器

EventMachine


本文主要是

  • EventMachine如何建一个简单的Echo服务器
  • post_init, unbind, receive_date 方法

EchoServer

如下代码,是建立一个简单的EchoServer

    
    
  1. #!/usr/bin/env ruby
  2. require 'rubygems'
  3. require 'eventmachine'
  4. class EchoServer < EM::Connection
  5. def post_init
  6. puts "client connection"
  7. end
  8. def unbind
  9. puts "client disconnection"
  10. end
  11. def receive_data(data)
  12. puts "received #{data} from client"
  13. send_data ">> #{data} from server"
  14. end
  15. end
  16. EM.run do
  17. EM.start_server '0.0.0.0', 9000, EchoServer
  18. puts "Server runnning on port 9000"
  19. end

分析 
1. 所有的代码都运行在EM.run 中 
2. EM.run不能运行阻塞的代码,比如HTTP::Get 等,也不能运行 do while 等代码段 
3. 使用 start_server(ip,port, ServerName) 开启一个Server 
4. Server继承自 Connection 
5. post_init: connect 建立马上就会访问的方法 
6. unbind: 失去connection后会访问的方法 
7. receive_data: 客户端每次访问向服务器发送数据的时候,都会访问的方法。主要用于接收来自客户端得大数据,比如超过100M的文件上传或者其他,类似于nginx中的chunk功能.

post_init, unbind, receive_date 三个方法有点类似于

    
    
  1. begin
  2. post_init
  3. while(1)
  4. receive_date
  5. end
  6. ensure
  7. unbind
  8. end

可以使用如下命令测试

    
    
  1. telnet 0.0.0.0 9000

EchoClient

    
    
  1. #!/usr/bin/env ruby
  2. require 'rubygems'
  3. require 'eventmachine'
  4. class EchoClient < EM::Connection
  5. def initialize(user)
  6. @user = user
  7. end
  8. def post_init
  9. puts "connected"
  10. send_data "Hello from #{@user}"
  11. end
  12. def unbind
  13. puts "disconnected"
  14. end
  15. def receive_data(data)
  16. puts "received #{data}"
  17. close_connection
  18. EM.stop
  19. end
  20. end
  21. EM.run do
  22. EM.connect 'localhost', 9000, EchoClient, ARGV[0]
  23. end
  1. 使用EM.connect方法启动一个Client,并且接收一个参数
  2. EchoClient继承自Connection
  3. 上面的代码在接收一次数据后,会关闭连接 close_connection, 并且调用EM.stop停止EM
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值