peterc (owner)

Revisions

gist: 90280 Download_button fork
public
Public Clone URL: git://gist.github.com/90280.git
Embed All Files: show embed
chatserver.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# 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