Created
April 4, 2009 19:02
-
-
Save peterc/90280 to your computer and use it in GitHub Desktop.
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
# Basic Ruby event driven "chat" server | |
# Heavily based on example code at http://rev.rubyforge.org/rdoc/ | |
# Works on Ruby 1.9.1 - not tested on 1.8. | |
require 'rev' | |
# Configuration | |
HOST = 'localhost' | |
PORT = 1234 | |
# The chat server class | |
class ChatServerConnection < Rev::TCPSocket | |
# Keep track of all connections | |
@@conns = [] | |
def on_connect | |
puts "#{remote_addr}:#{remote_port} connected" | |
@@conns << self | |
write "Welcome to the chat server. 'quit' to shut down.\n" | |
end | |
def on_close | |
puts "#{remote_addr}:#{remote_port} disconnected" | |
@@conns.delete!(self) | |
end | |
def on_read(data) | |
evloop.stop if data =~ /quit/ | |
@@conns.each do |conn| | |
next if conn == self | |
conn.write "#{remote_port} says: #{data}" | |
end | |
end | |
end | |
# Start the chat server | |
server = Rev::TCPServer.new('localhost', PORT, ChatServerConnection) | |
server.attach(Rev::Loop.default) | |
puts "Chat server listening on #{HOST}:#{PORT}" | |
Rev::Loop.default.run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment