Back

ruby - 使用socket (同步和异步两种方式)

发布时间: 2019-03-07 02:45:00

同步方式最简单。 

参考:

require 'socket'
hostname = 192.168.0.8
port = 8800
client = TCPSocket.open hostname, port
# 向服务器发送请求
client.send message, 0

puts "==开始接受服务器数据..."
# 打印服务器返回的结果
while line = client.gets
  puts line.chop
end
puts "==服务器数据接收完毕..."

## 关闭client
client.close

异步方式需要用到第三方库。 

考察了一下  https://github.com/socketry/async 这个是个基本 的。 要使用下面这个。

https://github.com/socketry/async-io

require 'async/io'

def echo_server(endpoint)
	Async do |task|
		# This is a synchronous block within the current task:
		endpoint.accept do |client|
			# This is an asynchronous block within the current reactor:
			data = client.read(512)
			
			# This produces out-of-order responses.
			task.sleep(rand * 0.01)
			
			client.write(data.reverse)
		end
	end
end

def echo_client(endpoint, data)
	Async do |task|
		endpoint.connect do |peer|
			result = peer.write(data)
			
			message = peer.read(512)
			
			puts "Sent #{data}, got response: #{message}"
		end
	end
end

Async do
	endpoint = Async::IO::Endpoint.tcp('0.0.0.0', 9000)
	
        # 创建一个server 
	server = echo_server(endpoint)
	
	5.times.collect do |i|
		echo_client(endpoint, "Hello World #{i}")
	end.each(&:wait)
	# 关闭这个server
	server.stop
end

Back