Skip to content

Instantly share code, notes, and snippets.

@doughsay
Created August 4, 2017 03:51
Show Gist options
  • Save doughsay/ef09073bcb429072a7729d6699d7af0d to your computer and use it in GitHub Desktop.
Save doughsay/ef09073bcb429072a7729d6699d7af0d to your computer and use it in GitHub Desktop.
Crystal Echo Server
require "socket"
def handle_connection(socket, client_id)
puts "#{client_id}: client connected"
loop do
message = socket.gets
if message
puts "#{client_id}: received #{message}"
socket << message + "\n"
else
puts "#{client_id}: client left"
break
end
end
end
server = TCPServer.new(1234)
next_client_id = 0
loop do
if socket = server.accept?
client_id = next_client_id
next_client_id += 1
spawn handle_connection(socket, client_id)
else
break
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment