To send a JSON message to a TCP server in Ruby, you will need to use the socket
library, specifically the Socket
class. Here is an example code snippet to demonstrate the process:
main.rb353 chars18 lines
In this example, we first require the socket
library and the json
library. We then set up the TCP connection by specifying the hostname and port number for the server we want to connect to, and we create a new TCPSocket
object to establish the connection.
Next, we create a JSON message by defining a Ruby hash with some example data, and we use the JSON.generate
method to convert the hash into a JSON-encoded string.
Finally, we send the JSON message to the server using the puts
method of the TCPSocket
object, and we close the connection with the close
method.
Note that this is just a basic example to give you an idea of how to send a JSON message over TCP. In real-world scenarios you will likely need to handle errors, timeouts, and other edge cases, so be sure to consult the Ruby documentation and best practices guides for more information.
gistlibby LogSnag