How to Make a Client/Server Connection in Ruby

Aug 10, 2015 03:04 PM
Aug 11, 2015 06:24 PM

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...

635747894207035234.jpg

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...

635748888787928447.jpg

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...)

635748889026210268.jpg

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?

Comments

No Comments Exist

Be the first, drop a comment!