Created
August 4, 2017 03:51
-
-
Save doughsay/ef09073bcb429072a7729d6699d7af0d to your computer and use it in GitHub Desktop.
Crystal Echo Server
This file contains hidden or 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" | |
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