User login
Recent comments
- Yes, my socket code is
3 weeks 6 days ago - Yes, I've been putting it off
4 weeks 1 day ago - Good work
4 weeks 2 days ago - @thread isn't made until
5 weeks 5 days ago - rick
5 weeks 5 days ago - Not that I'm aware of, but
5 weeks 5 days ago - GServer
5 weeks 5 days ago - mandriva
6 weeks 9 hours ago - Unfortunately that doesn't
6 weeks 16 hours ago - comes with music
6 weeks 21 hours ago
Blogroll
Threaded Networking in Ruby
snuxoll — Fri, 10/10/2008 - 21:04
Today in #ruby on Freenode someone who was working on an IRC bot was showing off their code and pointed out that it couldn't maintain more than one connection at a time. While I already had a IRC specific chunk of code I used myself to show him, I figured a more general solution would be a good idea. As such I figured I'd encapsulate a network connection in a simple class, so here you go!
# General purpose wrapper for network connections class NetworkConnection attr_reader :hostname, :port, :thread # Creates a new instance of NetworkConnection with the # specified hostname and port def initialize(hostname, port) @hostname = hostname @port = port end # Connects to the specified hostname and port given in new def connect @thread = Thread.new do @socket = TCPSocket.new(@hostname, @port) @socket.each { |line| @block.call(line) } end end # Closes the socket def disconnect @socket.close end # Takes a block of code to be called on each line recieved def on_recv(&block) @block = block end # Sends text to the socket def send(text) @socket.send(text + '\r\n', 0) end end
So now, the usual sample usage!
connection = NetworkConnection.new("irc.freenode.net", 6667) connection.on_recv { |line| puts line } connection.connect
Obviously this sample code will exit right after the connection is made, since the connection is maintained in a separate ruby thread. I'll leave it up to you to actually find some use in this, but there you go.
Search
Recent MP3 Purchases
Support Your Blogger
Hey, I need to eat too, chip in a dollar or chip in twenty, it's up to you.












GServer
Anonymous — Sat, 10/11/2008 - 02:50Doesn't Ruby's included GServer library do something similar?
Not that I'm aware of, but
snuxoll — Sat, 10/11/2008 - 03:47Not that I'm aware of, but this was meant to be a simple way to show how to do threaded networking in ruby apps, so take it for what it's worth.
----
Stefan Nuxoll
rick
Anonymous — Sat, 10/11/2008 - 11:26what is @thread's initial value? It's not mentioned anywhere else in the class.
@thread isn't made until
snuxoll — Sat, 10/11/2008 - 11:50@thread isn't made until NetworkConnection#connect is called, and when it is created it's the instance of the worker thread that listens to the socket for incoming data.
Edit: Aaah, I see why you asked that, I made a mistake in my code.
should be
I have corrected it in the post now.
----
Stefan Nuxoll
Post new comment