Skip to content

Instantly share code, notes, and snippets.

@proudlygeek
Created February 8, 2012 08:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save proudlygeek/1766748 to your computer and use it in GitHub Desktop.
Save proudlygeek/1766748 to your computer and use it in GitHub Desktop.
Basic Ruby Chat
# encoding: utf-8
require 'socket'
class Chatty
def initialize
@clients = []
end
def run
Socket.tcp_server_loop 8080 do |sock, client_addrinfo|
puts "Incoming connection from #{client_addrinfo.ip_address}"
@clients << {
:socket => sock,
:username => sock.gets.chomp
}
Thread.new do
begin
while line = sock.gets
break if line =~ /quit/
@clients.each do |client|
client[:socket].puts "#{client[:username]} said “#{line.chomp}”"
end
end
ensure
puts "#{client_addrinfo.ip_address} quits!"
p @clients
sock.close
end
end
end
end
end
a = Chatty.new
a.run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment