Skip to content

Instantly share code, notes, and snippets.

@genericpenguin
Created April 26, 2018 22:33
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 genericpenguin/23148067992756e5f333623428e0416e to your computer and use it in GitHub Desktop.
Save genericpenguin/23148067992756e5f333623428e0416e to your computer and use it in GitHub Desktop.
TCPSocket closing connection on spawn
require "socket"
class ConnectionManager
@client : TCPSocket
@channel_send : Channel(String)
@channel_receive : Channel(String)
def initialize(server, port)
@client = TCPSocket.new(server, port)
@channel_send = Channel(String).new
@channel_receive = Channel(String).new
end
def handle_send
puts "Before handle_send spawn: @client.closed? : #{@client.closed?}"
spawn do
until @client.closed?
puts "Waiting for messages..."
msg = @channel_send.receive
@client.write(msg.to_slice)
puts "Sent message"
end
end
rescue IO::EOFError
puts "Server disconnected"
ensure
puts "handle_send closing client"
@client.close
end
def handle_receive
puts "Before handle_receive spawn: @client.closed? : #{@client.closed?}"
spawn do
until @client.closed?
message = @client.gets || ""
@channel_receive.send(message)
end
end
rescue IO::EOFError
puts "Server disconnected"
ensure
puts "handle_receive closing client"
@client.close
end
def start
handle_receive()
handle_send()
end
def send(msg)
@channel_send.send(msg)
end
def receive
@channel_receive.receive
end
end
cm = ConnectionManager.new("localhost", 9000)
cm.start
cm.send("Initial connection\n")
sleep
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment