Ruby网络编程(1)

Ruby网络编程(1)

编程 Ruby Socket thread
关键字: TCPSocket TCPServer  
这个例子是这样的:客户端连上服务器后,服务器向客户端的终端显示服务器的时间,然后将来自客户端的网络连接养关闭。 
Ruby网络编程(1)_第1张图片 


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. }  

这样的话,每有一个客户端连接上来,就会在服务器端启动一个线程来处理请求。

你可能感兴趣的:(编程,网络,socket,tcp,服务器,Ruby)