From Java Socket to Ruby Socket

Hi All,

I am a newbie of Ruby, I met a problem when dealing with converting
java's socket programing into Ruby Socket code. I am trying to control a
remote relay board using ruby.

MY Java code is :

// using java Socket
Socket s = new Socket(hostname, port);

// raw streams
OutputStream rawout = s.getoutPutStream();
InputStream rawin = s.getInputStream();
BufferedOutputStream buffOut = new BufferedOutputStream(rawOut);

//Streams to allow easy manipulation of ints/string etc
DataOutputStream out = new DataOutputStream (bufferOut);
DataInputStream in = new DataInputStream(rawIn);

// send the command to the board
out.write(Integer.parseInt(firstCommand);
out.write(Integer.parseint(SecondCommand);

out.flush

s.setTimeout(1000);

System.out.println(in.read);

···

******************************************************
Ruby Code:

require 'socket'

begin
Serv = TCPSocket.new(hostIPAddress, port)
Serv.write(firstCommand.to_i)
Serv.write(SecondeCommand.to_i)
Serv.flush
ServResponse = Serv.recv(100)
puts ServResponse
Serv.close
rescue=>myException
puts "Exception happens: #{myException}"
end

My java code is working very well, however, the ruby code does not work
correctly, it is always waiting at the recv methods.

Since ruby has little detailed documents about its Socket programming,
it is an headache for us.

Thanks,

Daniel

--
Posted via http://www.ruby-forum.com/.

Serv.write(firstCommand.to_i)
Serv.write(SecondeCommand.to_i)

Write converts its argument to a string.

For example:

class Fixnum
  def to_s
    "hello!"
  end
end

STDOUT.write 42
STDOUT.write "\n"

This prints "hello!", not 42.

I think you want putc:

Serv.putc firstCommand.to_i
Serv.putc SecondeCommand.to_i # spelling?

BTW, generally variables begin with lowercase letters in Ruby.

···

--
Posted via http://www.ruby-forum.com/\.

Dan Connelly wrote in post #1065181:

Serv.write(firstCommand.to_i)
Serv.write(SecondeCommand.to_i)

Write converts its argument to a string.

For example:

class Fixnum
  def to_s
    "hello!"
  end
end

STDOUT.write 42
STDOUT.write "\n"

This prints "hello!", not 42.

I think you want putc:

Serv.putc firstCommand.to_i
Serv.putc SecondeCommand.to_i # spelling?

BTW, generally variables begin with lowercase letters in Ruby.

Thanks Dan, It works!

Daniel

···

--
Posted via http://www.ruby-forum.com/\.