create a tcp client on a specific port in ruby

To create a TCP client on a specific port in Ruby, you can use the socket library. Here's a basic example:

main.rb
require 'socket'

hostname = 'localhost'
port = 1234

# establish a connection
socket = TCPSocket.open(hostname, port)

# send data to the server
socket.puts "Hello, server!"

# receive data from the server
response = socket.gets
puts "Server says: #{response}"

# close the connection
socket.close
299 chars
18 lines

In this example, we first define the hostname and port that we want to connect to. We then use the TCPSocket class to establish a connection to the server. Once the connection is established, we can send data to the server using socket.puts, and receive data from the server using socket.gets.

Finally, we close the connection using socket.close. Note that it's generally a good practice to wrap TCPSocket.open in a begin/rescue block to handle any potential errors.

related categories

gistlibby LogSnag