关键字:
TCPSocket TCPServer
这个例子是这样的:客户端连上服务器后,服务器向客户端的终端显示服务器的时间,然后将来自客户端的网络连接养关闭。
my_tcp_server.rb
server.accept这个方法会一直挂着,直到有客户端连上来为止。
my_tcp_client.rb
然而大多数的服务器是支持多个客户端的连接的,在Ruby中可以用线程来很容易地做到这一点。
我将以上的my_tcp_server.rb中的服务器代码修改一下:
这样的话,每有一个客户端连接上来,就会在服务器端启动一个线程来处理请求。
这个例子是这样的:客户端连上服务器后,服务器向客户端的终端显示服务器的时间,然后将来自客户端的网络连接养关闭。
my_tcp_server.rb
- require 'socket' # Get sockets from stdlib
- server = TCPServer.open(2000) # Socket to listen on port 2000
- loop { # Servers run forever
- client = server.accept # Wait for a client to connect
- client.puts(Time.now.ctime) # Send the time to the client
- client.puts "Closing the connection. Bye!"
- #client.write("dd")
- client.close # Disconnect from the client
- }
server.accept这个方法会一直挂着,直到有客户端连上来为止。
my_tcp_client.rb
- require 'socket' # Sockets are in standard library
- hostname = 'localhost'
- port = 2000
- s = TCPSocket.open(hostname, port)
- while line = s.gets # Read lines from the socket
- puts line.chop # And print with platform line terminator
- end
- #streamSock.send( "Hello\n" )
- #str = streamSock.recv( 100 )
- #print str
- s.close # Close the socket when done
然而大多数的服务器是支持多个客户端的连接的,在Ruby中可以用线程来很容易地做到这一点。
我将以上的my_tcp_server.rb中的服务器代码修改一下:
- require 'socket' # Get sockets from stdlib
- server = TCPServer.open(2000) # Socket to listen on port 2000
- loop { # Servers run forever
- Thread.start(server.accept) do |client|
- client.puts(Time.now.ctime) # Send the time to the client
- client.puts "Closing the connection. Bye!"
- client.close # Disconnect from the client
- end
- }
这样的话,每有一个客户端连接上来,就会在服务器端启动一个线程来处理请求。