Created
February 8, 2012 08:20
-
-
Save proudlygeek/1766748 to your computer and use it in GitHub Desktop.
Basic Ruby Chat
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
# 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