ruby非阻塞式socket编程--写飞信客户端的经验总结

最近在使用ruby编写飞信客户端时,遇到TCPSocket的阻塞问题,socket总是直接挂死或者超时失败。经过一番探索,下面的方法颇有奇效,终于可以成功发短信啦:
require "socket"

class SIPC
	def initialize(sipc_addr)
		puts sipc_addr #uri = "221.176.31.33:8080"
		uri = sipc_addr.split(":")
		@socket = TCPSocket.new(uri[0], uri[1].to_i)
	end

	# send SIP-C request
	def request(sip_request)
		puts sip_request
		@socket.write_nonblock(sip_request)
		#@socket.write(sip_request) also works

		#select,read_nonblock and rescue is the key
		IO.select [@socket]
		res = ""
		begin
			while chunk = @socket.read_nonblock(4096)
				res = res + chunk
			end
		rescue
		end
		puts res 
		return res 
	end
end

你可能感兴趣的:(编程,C++,c,socket,Ruby)