Last active
August 29, 2015 14:16
-
-
Save eladmeidar/c54fc8697de59c268d9e to your computer and use it in GitHub Desktop.
Chat Client
This file contains hidden or 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
require "socket" | |
class Client | |
def initialize(host, port) | |
@server = TCPSocket.open( host, port ) | |
@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 the username:" | |
@request = Thread.new do | |
loop { | |
msg = $stdin.gets.chomp | |
@server.puts( msg ) | |
} | |
end | |
end | |
end | |
Client.new("104.131.58.31", 3333) |
This file contains hidden or 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
require "socket" | |
require 'colorize' | |
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_pair 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} Connected" | |
@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_pair do |other_name, other_client| | |
unless other_name == username | |
other_client.puts "#{username.to_s.on_green}: #{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