Javatpoint Logo
Javatpoint Logo

Ruby Socket Programming

Sockets are the end points of a network communication channel, where client and server communicate to each other. They can communicate either on same machine or on different machines.

Types of socket:

  • TCP Socket
  • UDP Socket
  • UNIX Socket

There are two levels of socket, high and low. Low level access allows you to work on sockets that are supported by your system. It allows the implementation of both connectionless and connection oriented protocols. High level access allows you to work on network protocols like HTTP and FTP.

Example1

server1.rb

In the above code, the pre installed socket module need to be included. We are using 2017 port on our system. You can use any port.

Start a loop, accept all connections made to port 2017 and send data to the client over socket networking.

Lastly, close the socket.

client1.rb

In the above code, the pre installed socket module need to be included. Create a socket and connect it to port 2017.

create a while loop to fetch all information sent over the socket.

Lastly, close the socket.

Output:

Go to the terminal, change to the directory to which you have saved the above two files. We have saved it in our Desktop directory.

Now to execute these files, we need to have the required permission. Run the following command in the terminal,

This command will make all the Ruby files executable present in this directory.

Ruby Socket programming 1

Now open two terminals. In the first terminal execute server script and in the second terminal execute client script with the following command.

Ruby Socket programming 2


Multiple clients socket programming

For multiple clients overs a socket programming, a loop and some threads will be needed to accept and respond to multiple clients.

Example2

server3.rb

In the above code, server will have the same port as client side to establish connection. Here we need one thread per connected user to handle all the possible users.

The run method verify whether an entered name is unique or not. If username already exists, connection will be killed otherwise connection will be established.

The listen_user_messages method listen to the user messages and send them to all the users.

client3.rb

In the above code, class Client is created to handle users.

Two threads are created in send and listen methods so that we can read/write messages at the same time.

Output:

Below snapshot shows chatting between two clients.

Ruby Socket programming 3

Output on server terminal is shown below.

Ruby Socket programming 4






Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


B.Tech / MCA