Browse | Submit A New Snippet | Create A Package

 

Ruby Chat Server

Type:
Full Script
Category:
Other
License:
GNU General Public License
Language:
Ruby
 
Description:
Runs a Chat Server on port 7680. Fairly basic, works with telnet to send/receive. Start to a project I'm thinking about doing over the summer.

Versions Of This Snippet::

Christopher Kruse
Snippet ID Download Version Date Posted Author Delete
1430.12006-04-08 15:09Christopher Kruse

Download a raw-text version of this code by clicking on "Download Version"

 


Latest Snippet Version: :0.1

require 'socket'
class ChatServer

   def initialize(port) #Instantiating the server
      @sockets_in = Array.new
      @serv_sock = TCPServer.new("",port)
      @serv_sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_REUSEADDR, 1)
      puts "Chat server started on port #{port}."
      @sockets_in.push(@serv_sock)
   end

   def run # The runtime code for the server
      while true
         someone_there = select(@sockets_in, nil, nil, nil)
         if someone_there != nil #Someone IS there, maybe wanting to talk?
            for socket in someone_there[0] #Check the sockets array
               #Do we have a connect,...
               if socket == @serv_sock then
                  accept_new
               else
               #...or did they leave,...
                  if socket.eof? then #If it sends an end of file notice - client disconnected.
                     str = "Client left #{socket.peeraddr[2]}:#{socket.peeraddr[1]}."
                     broadcast_string(str,socket)
                     socket.close
                     @sockets_in.delete(socket)
                  else
               #...or are they talking?
                     str = "#{socket.peeraddr[2]}:#{socket.peeraddr[1]} says: #{socket.gets}"
                     broadcast_string(str,socket)
                  end
               end
            end
         end
      end
   end

   private

   def broadcast_string(str,omit_sock) #Broadcasts the string to all available receiving sockets.
      @sockets_in.each do |client_sock| #each socket in the @sockets_in array do this:
         if client_sock != @serv_sock && client_sock != omit_sock #if it's not the server socket, and not the one that sent it...
            client_sock.write(str) #...write it to the client.
         end
      end
      #and just to keep track on the server end...
      puts(str)
   end

   def accept_new #accepts a new connection.
      new_sock = @serv_sock.accept
      @sockets_in.push(new_sock) #add new socket to sockets array.
      new_sock.write("Welcome to Ruby Chat!") #let them feel welcome.
      str = "Someone joined (#{new_sock.peeraddr[2]}:#{new_sock.peeraddr[1]})."
      broadcast_string(str,new_sock) #let everyone know someone came in.
   end

end

myChat = ChatServer.new(7680)
myChat.run
		

Submit a new version

You can submit a new version of this snippet if you have modified it and you feel it is appropriate to share with others..