Basic Ruby TCP Server & Client Example
TCP (Transmission Control Protocol and TCP/IP when utilized over the Internet Protocol) facilitates computer devices to reliably exchange messages over a network connection. It is used by many high-level protocols including but not limited to HTTP, FTP, IMAP, SMTP and SSH. In addition ISO8583 financial messaging (ex: credit card processing) is also handled through TCP/IP.
As with any use case, socket programming with Ruby is simple. Here we will look into a simple TCP server and client setup with just a few lines of Ruby. The server will greet the client with the visitor number and the current time. The client will print the message transmitted from the server to the console every time it is executed.
Instructions
First, create a server.rb
file in your project directory. This file will run the TCP server listening to a specified port and respond to incoming connections.
require 'socket'
server = TCPServer.new('localhost', 3002)
request_count = 0
loop do
client = server.accept
request_count += 1
client.puts "Welcome! You are visitor ##{request_count}"
client.puts "Time: #{Time.now}"
client.close
end
I believe the code is more or less self-explanatory even for someone new to Ruby. That is the magic of Ruby, it's mostly English. The first line is the shebang, basically, I am telling the operating system to use Ruby to execute this command. You don't need it, but I like it that way.
Now that you have a TCP server, let's write a simple client (file name client.rb
) to connect to the server.
require 'socket'
socket = TCPSocket.new('localhost', 3002)
while line = socket.gets
puts line
end
socket.close
To run the server use
ruby server.rb
To connect to the server from the client, run:
jdeen@iMac:/Volumes/Dev/JDeen/Projects/Tutes/Socket|
⇒ ruby client.rb
Hello from the server!
Time: 2022-07-16 21:05:11 +0530
Request: 1
jdeen@iMac:/Volumes/Dev/JDeen/Projects/Tutes/Socket|
⇒ ruby client.rb
Hello from the server!
Time: 2022-07-16 23:05:50 +0530
Request: 2
That's it!
About the Author
Ziyan Junaideen -
Ziyan is an expert Ruby on Rails web developer with 8 years of experience specializing in SaaS applications. He spends his free time he writes blogs, drawing on his iPad, shoots photos.