Skip to content

Instantly share code, notes, and snippets.

@elorest
Created November 30, 2018 17:53
Show Gist options
  • Save elorest/b47fffb6f6997e0532a5e97769da7849 to your computer and use it in GitHub Desktop.
Save elorest/b47fffb6f6997e0532a5e97769da7849 to your computer and use it in GitHub Desktop.
require "socket"
require "readline"
CL = STDOUT.tty? ? "\u001b[0G" : "\u000d \u000d"
CLEAR = STDOUT.tty? ? "\u001b[2K" : "\u000d"
name = ""
def clear(count)
print CL * count
end
class NikClient
def self.client
@@client ||= TCPSocket.new("127.0.0.1", 3002)
end
def self.refresh_client
@@client = TCPSocket.new("127.0.0.1", 3002)
end
def self.send(msg)
loop do
client.write msg.to_slice
break
rescue e
puts e.message
sleep 1
client.close
@@client = TCPSocket.new("127.0.0.1", 3002)
end
end
end
spawn do
collection = ""
while (b = NikClient.client.read_byte)
unless b == 10
collection += b.chr
else
clear(name.size)
puts collection
collection = ""
print name
end
end
end
puts "Please enter name: "
name = gets.to_s + ":> "
NikClient.client << (name + "\n")
puts "================================================================================\n"
loop do
print name
message = gets.to_s
message += "\n"
NikClient.send message
end
require "socket"
clients = [] of TCPSocket
def send_to_groups(clients : Array(TCPSocket), msg : String, name : String)
clients.each do |client|
puts "Sending message to client: #{client}"
client.write "#{name}#{msg}\n".to_slice
end
end
server = TCPServer.new("0.0.0.0", 3002)
while client = server.accept
puts "new client connected."
clients << client
spawn do
proc = ->(client : TCPSocket) do
name = client.gets.to_s
puts name
client.write "Hello #{name}. Enjoy!\n".to_slice
comp = ""
while (b = client.read_byte)
print b.chr
unless b == 10
comp += b.chr
else
# client.write("=> received!\n".to_slice)
send_to_groups(clients.reject(&.== client), comp, name)
comp = ""
end
end
rescue ex
puts ex.message
end
proc.call(client)
clients.delete(client)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment