Rubyでサーバを作ってクライアントにデータを配信 vol.1

これはRubyで作ったソケットサーバに接続してきたクライアントにデータを配信するための勉強上の知見です。

require "socket"

port = if ARGV[0] then ARGV[0] else 'echo' end
gate = TCPServer.open(port)

sock = gate.accept
gate.close

while msg = STDIN.gets
    sock.puts msg.upcase
end
sock.close

サーバを立ち上げる

% ruby multisend00.rb 9999

クライアントはワンライナーで。

ruby -rsocket -e 's=TCPSocket.new("localhost",9999);while a=s.gets;puts a end'

サーバ上で、「abc」と入力してエンターを押すと、 クライアント画面にABCと大文字になって出てくる。 f:id:xibbar:20150814160223p:plain