Created
February 1, 2020 13:54
-
-
Save Prigin/3ee516a8cca7151d4dc7928e10f372e1 to your computer and use it in GitHub Desktop.
mkdev
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
require 'socket' | |
class Server | |
attr_reader :queue | |
def initialize(log) | |
@srv_sock = TCPServer.new('localhost', 3000) | |
@srv_sock.listen(2) | |
@queue = Queue.new | |
@log = log | |
@conn_list = [] | |
Struct.new('Connection', :nick, :sock, :rcv_thr) | |
@loops = [master_loop, accept_loop] | |
end | |
def accept_loop | |
Thread.new do | |
loop do | |
conn = @srv_sock.accept | |
nickname = conn.gets.chomp | |
rcv_thr = Thread.new(conn, nickname) do |sock, nick| | |
begin | |
loop { @queue << [:log, sock.gets.chomp] } | |
rescue StandardError | |
disconnect(nick) | |
end | |
end | |
@queue << [:conn_list, Sruct::Connection.new(nick, conn, rcv_thr)] | |
end | |
end | |
end | |
def master_loop | |
Thread.new do | |
loop do | |
tag, obj = @queue.deq | |
if tag == :log | |
@log.write << obj | |
elsif tag == :conn_list | |
@conn_list << obj | |
elsif tag == :disconnect | |
disconnect(obj) | |
end | |
end | |
end | |
end | |
def send(msg, nick = nil) | |
@conn_list.each { |conn| conn[:sock].puts(msg) unless conn[:nick] == nick } | |
end | |
def disconnect(nick) | |
@conn_list.reject do |conn| | |
next if conn[:nick] == nick | |
conn[:rcv_thr].stop | |
conn[:sock].close | |
true | |
end | |
end | |
end | |
class LogWriter | |
def initialize(container, log) | |
@container = container # [] | |
@log = log | |
@index = container.index(:_data) | |
end | |
def write(str) | |
@container[@index] = str | |
@log << @container | |
end | |
end | |
class Screen | |
attr_accessor :queue, :loop | |
def initialize(hsh) | |
@scr_objects = hsh | |
@queue = Queue.new | |
@loop = Thread.new do | |
loop do | |
obj, str = @queue.deq | |
hsh[obj].push(str) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment