How To: Make a Client/Server Connection in Ruby

Make a Client/Server Connection in Ruby

Recently, I've been learning Ruby as a second scripting language. But one topic I never covered with the many lessons online were sockets. So I did some research and came up with a very simple client/server connection that sends a string over the socket.

The Client

First, the code...

As you can see, this is very simple as it only has 12 lines of code. Lets go through them one by one...

Line 1: The is the shebang It tells our system to use the ruby interpreter for this file.

Line 2: Ruby comes preinstalled with a socket module so we have to include it in this program.

line 4 & 5: Here we are setting some variables. You can set these to whatever you like but for the sake of this tutorial, I am connecting to my machine on port 2000.

line 7: Here is where we create the socket and connect to our target (in our case localhost @ port 2000)

line 9-11: This is a while loop to get all the information being sent over the socket

line 12: We close the socket

Save this as ruby-client.rb (or something along those lines)

The Server

Now the server code...

Let's go over the code...

line 1: shebang
line 2: include the socket module
line 3: Creates a socket to listen on port 2000
line 4: start of a loop
line 5: accept all connections made to port 2000
line 6: sends the data over the socket to the client
line 7: closes the socket

save it as ruby-server.rb

Final Product

Now that the code is complete, change to the directory in which you saved the programs. Now, we need to have the permissions to execute it. To do that, type the following:

chmod a+x *.rb
This command makes all ruby files in this directory executable by all users.

Now open two terminal.

In the first one, execute the server script. You won't see any output just yet.

In the second terminal, execute the client script. Hit enter and you'll see the the string we set to send when we connect to the server.

(It should look something like this...)

Additions

This is only a simple connection but, if you want me to add something to it to give it more usability, just ask. Or you can do it and post a link in the comments! Also, I want everyone's opinion. Should I start a series for Ruby. Like I teach the basics with some projects in there?

Just updated your iPhone? You'll find new emoji, enhanced security, podcast transcripts, Apple Cash virtual numbers, and other useful features. There are even new additions hidden within Safari. Find out what's new and changed on your iPhone with the iOS 17.4 update.

3 Comments

Yeah. Ruby has a lot more functionality that comes with it than python. I'm gonna start the series tomorrow I think.

Thank you, this really encouraged me to learn Ruby. You can make a very simple trojan from this script.

Share Your Thoughts

  • Hot
  • Latest