Skip to content

Instantly share code, notes, and snippets.

@tompng
Created June 5, 2018 03:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tompng/0ff8cf33046cb312dd66d55195c91eee to your computer and use it in GitHub Desktop.
Save tompng/0ff8cf33046cb312dd66d55195c91eee to your computer and use it in GitHub Desktop.
human_chat_server
require 'socket'
require 'cgi'
sv=TCPServer.new((ARGV[0]||3000).to_i)
chan={}
mainqueue=Queue.new
Thread.new{loop{s=sv.accept;Thread.new{
s.puts "HTTP/1.0 200 OK\r\nContent-type:text/html\r\n\r"
begin
l=s.gets
if /\?(?<a>.+)=(?<b>[^ ]+)/=~l
q=chan[a]
q<<CGI.unescape(b)
elsif l=~/ \/ /
queue=Queue.new
cid=rand.to_s
chan[cid]=queue
s.puts '<meta charset=utf-8>'
s.puts '<iframe name=a style=display:none></iframe>'
s.puts "<form target=a><input name=#{cid}></form>"
Thread.new{loop{queue<<nil;sleep 1} rescue 0}
loop{
msg,f=queue.deq
if msg
s.puts "<pre><b>#{f||:you}:</b>&nbsp;#{CGI.escape_html msg}</pre>"
if !f
s.puts "<script>document.querySelector('input').value=''</script>"
mainqueue<<[msg, queue]
end
else
s.puts
end
s.flush
}
end
rescue
ensure
queue.close rescue 0
s.close rescue 0
end
}}}
loop{
msg,res=mainqueue.deq
puts CGI.unescape msg
$><<'>'
res<<[gets,:bot] rescue 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment