Skip to content

Instantly share code, notes, and snippets.

@amit352
Forked from chikadance/tc.rb
Created June 16, 2019 07:46
Show Gist options
  • Save amit352/c40ad32434cc18fdaae509328efab0c6 to your computer and use it in GitHub Desktop.
Save amit352/c40ad32434cc18fdaae509328efab0c6 to your computer and use it in GitHub Desktop.
ruby: tcp socket sample(input line must end with \n)
#!/usr/bin/env ruby
# socket example - client side
# usage: ruby clnt.rb [host] port
require "socket"
if ARGV.length >= 2
host = ARGV.shift
else
host = "localhost"
end
print("Trying ", host, " ...")
s = TCPSocket.new("localhost", 3333)
print(" done\n")
print("addr: ", s.addr.join(":"), "\n")
print("peer: ", s.peeraddr.join(":"), "\n")
line = "a\n"
# must end with \n
p line
s.write(line)
print(s.readline)
s.close
# socket example - server side
# usage: ruby svr.rb
# this server might be blocked by an ill-behaved client.
# see tsvr.rb which is safe from client blocking.
require "socket"
gs = TCPServer.open(3333)
addr = gs.addr
addr.shift
printf("server is on %s\n", addr.join(":"))
socks = [gs]
loop do
nsock = select(socks);
next if nsock == nil
for s in nsock[0]
if s == gs
ns = s.accept
socks.push(ns)
print(s, " is accepted\n")
else
if s.eof?
print(s, " is gone\n")
s.close
socks.delete(s)
# single thread gets may block whole service
elsif str = s.gets
s.write(str)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment