Created
June 7, 2015 14:39
-
-
Save sai43/f2fddebd3a234fb920f6 to your computer and use it in GitHub Desktop.
Chat application in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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, Thank you for joining! Happy chatting" | |
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( 3000, "localhost" ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment