Created
April 21, 2014 04:21
-
-
Save chikadance/11132140 to your computer and use it in GitHub Desktop.
ruby: tcp socket sample(input line must end with \n)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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