Created
April 26, 2018 22:33
-
-
Save genericpenguin/23148067992756e5f333623428e0416e to your computer and use it in GitHub Desktop.
TCPSocket closing connection on spawn
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" | |
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