Do not spawn a thread by default

This allows users to implement better multi threading than me.
Or if someone just wants to fire and forget a client that should just
use the provided hooks then not detaching takes away the effort
of keeping the program running.

Imo it is an easier and more fun problem to have:

  "My client connects fine but my other ruby code does not run"

than

  "My program just quits when I run it"
This commit is contained in:
ChillerDragon 2022-11-01 15:32:47 +01:00
parent f7486c353f
commit 24fa105f66
3 changed files with 25 additions and 15 deletions

View file

@ -10,5 +10,5 @@ client.hook_chat do |msg|
puts "chat: #{msg}"
end
client.connect('localhost', 8303)
client.connect('localhost', 8303, detach: false)
```

View file

@ -34,10 +34,13 @@ class TwClient
@hooks[:chat] = block
end
def connect(ip, port)
if @thread_running
puts "Error: connection thread already running call disconnect() first"
return
def connect(ip, port, options = {})
options[:detach] = options[:detach] || false
if options[:detach]
if @thread_running
puts "Error: connection thread already running call disconnect() first"
return
end
end
@ip = ip
@port = port
@ -48,16 +51,13 @@ class TwClient
@netbase.connect(@s, @ip, @port)
@token = nil
send_ctrl_with_token
@thread_running = true
Thread.new do
p @s
until @signal_disconnect
tick
# todo: proper tick speed sleep
sleep 0.001
if options[:detach]
@thread_running = true
Thread.new do
connection_loop
end
@thread_running = false
@signal_disconnect = false
else
connection_loop
end
end
@ -68,6 +68,16 @@ class TwClient
private
def connection_loop
until @signal_disconnect
tick
# todo: proper tick speed sleep
sleep 0.001
end
@thread_running = false
@signal_disconnect = false
end
def send_msg(data)
@netbase.send_packet(data)
end

View file

@ -31,7 +31,7 @@ client.hook_chat do |msg|
puts "chat: #{msg}"
end
client.connect(args[:ip], args[:port])
client.connect(args[:ip], args[:port], detach: true)
loop do
sleep 2