Ruby网络编程(1)

关键字:[size=xx-large]TCPSocket TCPServer [/size]
这个例子是这样的:客户端连上服务器后,服务器向客户端的终端显示服务器的时间,然后将来自客户端的网络连接养关闭。
[img]http://bot.iteye.com/upload/picture/pic/38438/2070be77-cad8-3ce1-9774-38899bcc4e85.jpg[/img]


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
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值