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

#!/usr/bin/ruby   

require 'socket'   

  

server = TCPServer.open(2017)   

loop {   

    client = server.accept   

    client.puts "Hello. This is socket programming"   

    client.close   

}

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

#!/usr/bin/ruby   

require 'socket'   

  

hostname = 'localhost'   

port = 2017   

  

s = TCPSocket.open(hostname, port)   

  

while line = s.gets   

    puts line.chomp   

end   

s.close

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,

  1. chmod a+x *.rb  

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

#!/usr/bin/env ruby -w   

require "socket"   

class Server   

  def initialize( port, ip )   

    @server = TCPServer.open( ip, port )   

    @connections = Hash.new   

    @rooms = Hash.new   

    @clients = Hash.new   

    @connections[:server] = @server   

    @connections[:rooms] = @rooms   

    @connections[:clients] = @clients   

    run   

  end   

  

  def run   

    loop {   

      Thread.start(@server.accept) do | client |   

        nick_name = client.gets.chomp.to_sym   

        @connections[:clients].each do |other_name, other_client|   

          if nick_name == other_name || client == other_client   

            client.puts "This username already exist"   

            Thread.kill self   

          end   

        end   

        puts "#{nick_name} #{client}"   

        @connections[:clients][nick_name] = client   

        client.puts "Connection established..."   

        listen_user_messages( nick_name, client )   

      end   

    }.join   

  end   

  

  def listen_user_messages( username, client )   

    loop {   

      msg = client.gets.chomp   

      @connections[:clients].each do |other_name, other_client|   

        unless other_name == username   

          other_client.puts "#{username.to_s}: #{msg}"   

        end   

      end   

    }   

  end   

end   

  

Server.new( 2019, "localhost" )

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

#!/usr/bin/env ruby -w   

require "socket"   

class Client   

  def initialize( server )   

    @server = server   

    @request = nil   

    @response = nil   

    listen   

    send   

    @request.join   

    @response.join   

  end   

  

  def listen   

    @response = Thread.new do   

      loop {   

        msg = @server.gets.chomp   

        puts "#{msg}"   

      }   

    end   

  end   

  

  def send   

    puts "Enter your name:"   

    @request = Thread.new do   

      loop {   

        msg = $stdin.gets.chomp   

        @server.puts( msg )   

      }   

    end   

  end   

end   

  

server = TCPSocket.open( "localhost", 2019 )   

Client.new( server )

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

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *