Home > Blockchain >  How do I pass in the correct parameters for a UDP socket's send function in Ruby?
How do I pass in the correct parameters for a UDP socket's send function in Ruby?

Time:01-07

I'm trying to respond to a request using two UDP sockets. The server acting socket is getting a no implicit conversion to string error. I've checked that all parameters are of the correct objects. Please help me.

require 'socket'


socket = UDPSocket.new()
socket.bind('0.0.0.0',6666)
loop do
  command,sender = socket.recvfrom(24)
  ip = sender[3]
  resp = system(command)
  #sender[1] is the port of the sender. I've not used udp but that might be wrong.
  socket.send(resp, 0, ip.to_s, sender[1]) #no implicit conversion of true into String
end

CodePudding user response:

The error you are encountering is due to the fact that the resp variable, which is returned by the system method, is a boolean value (either true or false). However, the send method expects its first argument to be a string. When you pass a boolean value to send, it is unable to implicitly convert it to a string, hence the error message "no implicit conversion to string." To resolve this issue, you can convert the boolean value of resp to a string using the to_s method before passing it to send. This can be done like so:
socket.send(resp.to_s, 0, ip.to_s, sender[1])

Or you can return a different value from the system call, such as the output of the command or a custom message indicating success or failure.

CodePudding user response:

socket.send's first argument should be a string. You have supplied the return value of system(command) which is a boolean.

If you wish to capture the output of running a command, you should use backticks rather than system.

resp = `#{command.to_s}`
  • Related