Ruby网络编程(1)

关键字: TCPSocket TCPServer  
这个例子是这样的:客户端连上服务器后,服务器向客户端的终端显示服务器的时间,然后将来自客户端的网络连接养关闭。 
 


my_tcp_server.rb 
Ruby代码   收藏代码
  1. require 'socket'               # Get sockets from stdlib  
  2.   
  3. server = TCPServer.open(2000)  # Socket to listen on port 2000  
  4. loop {                         # Servers run forever  
  5.   client = server.accept       # Wait for a client to connect  
  6.   client.puts(Time.now.ctime)  # Send the time to the client  
  7.   client.puts "Closing the connection. Bye!"  
  8.   #client.write("dd")  
  9.   client.close                 # Disconnect from the client  
  10. }  


server.accept这个方法会一直挂着,直到有客户端连上来为止。 

my_tcp_client.rb 
Ruby代码   收藏代码
  1. require 'socket'      # Sockets are in standard library  
  2.   
  3. hostname = 'localhost'  
  4. port = 2000  
  5.   
  6. s = TCPSocket.open(hostname, port)  
  7.   
  8. while line = s.gets   # Read lines from the socket  
  9.   puts line.chop      # And print with platform line terminator  
  10. end  
  11.   
  12. #streamSock.send( "Hello\n" )    
  13. #str = streamSock.recv( 100 )    
  14. #print str    
  15.   
  16. s.close               # Close the socket when done  


然而大多数的服务器是支持多个客户端的连接的,在Ruby中可以用线程来很容易地做到这一点。 

我将以上的my_tcp_server.rb中的服务器代码修改一下: 
Ruby代码   收藏代码
  1. require 'socket'                # Get sockets from stdlib  
  2.   
  3. server = TCPServer.open(2000)   # Socket to listen on port 2000  
  4. loop {                          # Servers run forever  
  5.   Thread.start(server.accept) do |client|  
  6.     client.puts(Time.now.ctime) # Send the time to the client  
  7.     client.puts "Closing the connection. Bye!"  
  8.     client.close                # Disconnect from the client  
  9.   end  
  10. }  

这样的话,每有一个客户端连接上来,就会在服务器端启动一个线程来处理请求。
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值