How to fix a Ruby (server) deadlock communicating with a Java/scala (client)

101 Views Asked by At

I have a problem sending data over a TCPSocket if the server is on Ruby and the client is on Scala.

Scala always stops at in.readInt(). It looks like a deadlock but the Ruby server is running using Threads.

If Ruby is the client and Scala is the server there is no problem.

Ruby:

require 'socket'
require 'rjb'

Rjb.load("#{ENV['SCALA_HOME']}/lib/scala-library.jar:scala.jar")
Rjb.primitive_conversion = true

ScalaObject = Rjb.import('ruby.ScalaObject')

@port = nil

t = Thread.new do
  server = TCPServer.new(0)
  @port = server.addr[1]

  connection = server.accept

  puts "ruby: received #{connection.read(4).unpack('l>').first}"

  to_send = 5
  puts "ruby: sending #{to_send}"
  connection.write([to_send].pack('l>'))
  connection.flush
end

while @port.nil?
  sleep(0.1)
end

ScalaObject.start(@port)

t.join

Scala:

package ruby

import java.io._
import java.net._

object ScalaObject {
  def start(port: Int) {
    val socket = new Socket("localhost", port)

    val out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream, 65536))
    val in = new DataInputStream(new BufferedInputStream(socket.getInputStream, 65536))

    val to_send = 4
    println("scala: sending " + to_send.toString())

    out.writeInt(to_send)
    out.flush()

    println("scala: received " + in.readInt())
  }
}
0

There are 0 best solutions below