Socket Programming in Ruby Language
Socket programming is a fundamental aspect of network communication that enables data transfer between devices over a network. It’s a crucial skill for developers who want to bu
ild networked applications. Ruby, a versatile and elegant programming language, provides excellent support for socket programming. In this post, we’ll explore the basics of socket programming in Ruby, and we’ll provide practical examples to help you get started.Socket Basics
A socket is a communication endpoint that allows bidirectional data flow between two machines over a network. In Ruby, you can work with sockets using the ‘socket’ library. There are two types of sockets: TCP and UDP. TCP (Transmission Control Protocol) provides a reliable, connection-oriented communication, while UDP (User Datagram Protocol) offers a connectionless, lightweight communication.
Socket Programming in Ruby
- Creating a TCP Server
require 'socket'
server = TCPServer.new(8080)
loop do
client = server.accept
client.puts "Hello, client!"
client.close
end
In this example, we create a TCP server listening on port 8080. It accepts incoming connections, sends a greeting to the client, and then closes the connection.
- Creating a TCP Client
require 'socket'
client = TCPSocket.new('localhost', 8080)
response = client.gets
puts response
client.close
This code demonstrates how to create a TCP client that connects to a server running on ‘localhost’ and port 8080. It reads the server’s response and closes the connection.
- Creating a UDP Server
require 'socket'
server = UDPSocket.new
server.bind('0.0.0.0', 8080)
loop do
data, client = server.recvfrom(1024)
server.send("Hello, client!", 0, client[3], client[1])
end
This example creates a UDP server that listens on all available network interfaces and port 8080. It receives data from clients and sends a response.
- Creating a UDP Client
require 'socket'
client = UDPSocket.new
client.send("Hello, server!", 0, 'localhost', 8080)
response, _ = client.recvfrom(1024)
puts response
Here, we create a UDP client that sends a message to a server running on ‘localhost’ and port 8080. It then receives the server’s response.
Discover more from PiEmbSysTech
Subscribe to get the latest posts sent to your email.