Ruby Socket Programming
Ruby provides two levels of services for accessing the network. At the low level, you can access the operating system, which allows you to implement basic socket support for connection-oriented and connectionless protocols for both clients and servers.
Ruby uniformly supports application-level network protocols such as FTP, HTTP, and others.
Whether high-level or low-level, Ruby provides some basic classes that let you interact using many protocols such as TCP, UDP, and SOCKS, without being confined to the network layer. These classes also provide helper classes that let you easily read from and write to servers.
Next, let's learn how to do Ruby Socket programming
What are Sockets
When the application layer communicates data through the transport layer, TCP and UDP encounter the problem of providing concurrent service to multiple application processes at the same time. Multiple TCP connections or multiple application processes may need to transmit data through the same TCP protocol port. To distinguish different application processes and connections, many computer operating systems provide an interface called a socket (Socket) for applications to interact with the TCP/IP protocol, distinguishing network communication and connections between different application processes.
To generate a socket, there are mainly three parameters: the destination IP address for communication, the transport layer protocol used (TCP or UDP), and the port number used. Socket originally means "outlet". By combining these three parameters and binding them to an "outlet" Socket, the application layer can distinguish communication from different application processes or network connections through the socket interface with the transport layer, achieving concurrent service for data transmission.
Sockets Vocabulary Explained:
| Option | Description |
|---|---|
| domain | Specifies the protocol family to use, typically PF_INET, PF_UNIX, PF_X25, etc. |
| type | Specifies the socket type: SOCK_STREAM or SOCK_DGRAM. The Socket interface also defines raw sockets (SOCK_RAW), allowing programs to use low-level protocols |
| protocol | Usually assigned 0. |
| hostname | An identifier for the network interface:
|
A Simple Client
Below we write a simple client example with a given host and port. The Ruby TCPSocket class provides the open method to open a socket.
TCPSocket.open(hosname, port) opens a TCP connection.
Once you open a Socket connection, you can read from it just like an IO object. When finished, you need to close the connection just like closing a file.
The following example demonstrates how to connect to a specified host, read data from the socket, and finally close the socket:
Example
require
'
socket
'
Sockets is the standard library
hostname
=
'
localhost
'
port
=
2000
s
=
TCPSocket
.
open
(
hostname
,
port
)
while
line
=
s
.
gets
Read each line of data from the socket
puts
line
.
chop
Print to the terminal
end
s
.
close
Close the socket
A Simple Server
In Ruby, you can use the TCPServer class to write a simple server. A TCPServer object is a factory object for TCPSocket.
Now we use TCPServer.open(hostname, port) to create a TCPServer object.
Next, call the accept method of TCPServer, which waits for a client to connect to the specified port, and then returns a TCPSocket object representing the connection to that client.
Example
require
'
socket
'
Require the socket standard library
server
=
TCPServer
.
open
(
2000
)
Socket listens on port 2000
loop
{
Run the server indefinitely
client
=
server
.
accept
Wait for a client connection
client
.
puts
(
Time
.
now
.
ctime
)
Send the time to the client
client
.
puts
"
Closing the connection. Bye!
"
client
.
close
Close the client connection
}
Now, run the above code on the server to see the effect.
Multi-Client TCP Server
On the Internet, most services have a large number of client connections.
Ruby's Thread class makes it easy to create a multi-threaded server, where one thread handles a client connection while the main thread waits for more connections.
Example
require
'
socket
'
Require the socket standard library
server
=
TCPServer
.
open
(
2000
)
Socket listens on port 2000
loop
{
Run the server indefinitely
Thread
.
start
(
server
.
accept
)
do
|
client
|
client
.
puts
(
Time
.
now
.
ctime
)
Send the time to the client
client
.
puts
"
Closing the connection. Bye!
"
client
.
close
Close the client connection
end
}
In this example, the socket runs indefinitely, and when server.accept receives a client connection, a new thread is created and immediately begins processing the request. The main program immediately loops back and waits for a new connection.
A Tiny Web Browser
We can use the socket library to implement any Internet protocol. The following code shows how to fetch the content of a web page:
Example
require
'
socket
'
host
=
'
www.w3cschool.cc
'
web server
port
=
80
default HTTP port
path
=
"
/index.htm
"
the address of the file you want to fetch
This is an HTTP request
request
=
"
GET #{path} HTTP/1.0
\r
\n
\r
\n
"
socket
=
TCPSocket
.
open
(
host
,
port
)
Connect to a Server
socket
.
(
request
)
Send the request
response
=
socket
.
read
read the complete response
Split response at first blank line into headers and body
headers
,
body
=
response
.
split
(
"
\r
\n
\r
\n
"
,
2
)
body
Output result
To implement a web-like client, you can use a pre-built library for HTTP such as Net::HTTP.
The following code is equivalent to the previous code:
Example
require
'
net/http
'
the library we need
host
=
'
www.w3cschool.cc
'
web server
path
=
'
/index.htm
'
the file we want
http
=
Net
::
HTTP
.
new
(
host
)
Create a Connection
headers
,
body
=
http
.
get
(
path
)
Request the file
if
headers
.
code
==
"
200
"
check the status code
body
else
puts
"
#{headers.code} #{headers.message}
"
end
Above we have briefly introduced the use of sockets in Ruby. For more documentation, please see:Ruby Socket Library and Class Methods