79 lines
1.6 KiB
Ruby
79 lines
1.6 KiB
Ruby
#!/usr/bin/env ruby
|
|
|
|
require 'socket'
|
|
|
|
PORT = 6789
|
|
ROWS = 24
|
|
COLS = 40
|
|
VERSION = 0.01
|
|
|
|
server = TCPServer.new(PORT)
|
|
sockets = [server]
|
|
|
|
puts "PORT: #{PORT}"
|
|
puts 'Listening...'
|
|
|
|
buffer = ' '*ROWS*COLS
|
|
cont = 0
|
|
|
|
def new_buf_cont_out(buf, count, newtext)
|
|
buf = buf.dup
|
|
out = ''
|
|
nti = 0 # New Text Index
|
|
while nti < newtext.length
|
|
out << "#{VERSION}|"
|
|
out << ((count/COLS)+1).to_s + '|'
|
|
out << ((count%COLS)+1).to_s + '|'
|
|
loop do
|
|
out << newtext[nti]
|
|
buf[count] = newtext[nti]
|
|
count += 1
|
|
nti += 1
|
|
break if nti >= newtext.length
|
|
break if count%COLS == 0
|
|
end
|
|
count = 0 if count >= (ROWS*COLS)
|
|
out << "\n"
|
|
end
|
|
return [buf, count, out]
|
|
end
|
|
|
|
loop do
|
|
ready, = IO.select(sockets)
|
|
newtext = ''
|
|
|
|
ready.each do |sck|
|
|
if sck == server
|
|
client = server.accept
|
|
sockets << client
|
|
puts "Connection: #{client.peeraddr}"
|
|
client.puts new_buf_cont_out(buffer,0,buffer)[2]
|
|
client.puts new_buf_cont_out(buffer,cont-1,'')[2]
|
|
next
|
|
end
|
|
begin
|
|
|
|
msg = sck.gets
|
|
unless msg
|
|
puts "Disconnect: #{sck.peeraddr}"
|
|
sck.close
|
|
sockets.delete(sck)
|
|
next
|
|
end
|
|
ver, msg = msg.chomp.split('|',2)
|
|
next unless ver.to_f <= VERSION
|
|
next unless msg != nil
|
|
newtext << msg
|
|
rescue Errno::ECONNRESET, Errno::EPIPE
|
|
puts "Disconnect (err): #{sck.peeraddr}"
|
|
sck.close
|
|
sockets.delete(sck)
|
|
end
|
|
buffer, cont, out = new_buf_cont_out(buffer,cont,newtext)
|
|
clients = sockets - [server]
|
|
clients.each { |c| c.puts out }
|
|
#if out != ''
|
|
# puts "#{cont}: (#{(cont/COLS)+1},#{(cont%COLS)+1})"
|
|
#end
|
|
end
|
|
end
|