send a json message to a tcp server in ruby

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.rb
require 'socket'
require 'json'

# Set up the TCP connection
hostname = 'localhost'
port = 1234
client = TCPSocket.new(hostname, port)

# Create a JSON message
message = { name: 'John', age: 30, city: 'New York' }
json_message = JSON.generate(message)

# Send the JSON message to the server
client.puts json_message

# Close the connection
client.close
353 chars
18 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.

related categories

gistlibby LogSnag