Jruby, sockets and swing

Hi all.

I’m using jruby and swing to write a very small and simple client for
FairDJ (google it, it’s great :slight_smile: )

Somewhat simplified what the app does is

class FairDJClient
def initialize(host, user, pass)
@socket = TCPSocket.new(host, 4444)
#login stuff
end
def next
@socket.puts “next”
end
end

client = FairDJClient.new(host, user,pass)
MainWindow.new(client).

MainWindow in turn sets up some swing buttons and then does
next_button.add_event_listener {|event| client.next }

Now the strange thing is that when I use that socket I get a
Exception in thread “AWT-EventQueue-0”
org.jruby.exceptions.RaiseException: (Errno::EBADF) Bad file
descriptor

Attached is the code.

Why do I get this exception? Is this a general swing-problem in some
way or is it related to jruby somehow?

Regards
Erik

does it work in single threaded mode, like without swing?

Doing some quick testing shows that calling client.next from a
newly-spawned thread works in both ruby 1.9.2 and JRuby 1.6.0RC2.
Also, using a java.util.concurrent.BlockingQueue to pass the
client.next call from the AWT event handler back to the main thread
makes the call to client.next work as well. So apparently the problem
is just in trying to access the socket from the AWT thread
specifically.

If you’re interested in my workaround, here are the important bits.

in main

queue = LinkedBlockingQueue.new
client = FairDJClient.new(host, user, pass, queue)
gui = MainWindow.new(client)
while callable = queue.poll(5, TimeUnit::SECONDS)
callable.call unless callable.nil?
end

class FairDJClient
def next
@queue.put {
# didn’t see anything in the fairdj log when next was sent
# over the wire, so print to stdout as well
STDOUT.puts “NEXT!”
@socket.puts “next”
}
end
end

On Sun, Mar 13, 2011 at 10:26 AM, Anthony J. [email protected]
wrote:

makes the call to client.next work as well. So apparently the problem
is just in trying to access the socket from the AWT thread
specifically.

Out of curiosity, I ran my test on an OpenIndiana box as well, and
found that the original version works just fine (accessing the socket
from the AWT event thread), so it may only an issue with accessing the
socket from the AWT event thread on Mac OS X.