I'm working on a small ruby client that sends a continuous stream of information to a socket server (which is then passed on to other clients listening). I do not want to have to close the connection every time data is sent, however it seems that with ruby, the data is not sent until I close the connection. Is there another way to do this without reconnecting to the server? It is essential that the outgoing data is passed along as soon as it is sent by the client script.
Currently I have to do this within a loop:
s = TCPsocket.new('127.0.0.1',2000)
s.send('Hello World',0)
s.close
However, that means that I am constantly having to reconnect to the socket server, often in very quick succession. I would like to be able to connect to the socket server outside of the loop and close when the loop is done. If I do that now, the send data will all be sent at once when the 'close' is initiated.
Is it possible to keep the connection open while continuing to send information? I know this is possible in other languages and scripts as I have done it several times in AS3.
Thanks in advance.
To answer my own question (hopefully to the help of others), appending \000
after the message in the ruby socket.send('some message\000', 0)
works. To clarify, you can type this
socket = TCPsocket.new('127.0.0.1',2000)
socket.send('some message\000', 0)
Above will send a message without first to close the socket connection first (socket.close
). Also for reference is the ruby socket server, which I am using to broadcast to Flash.
require 'socket'
portnumber = 2000
socketServer = TCPServer.open(portnumber)
while true
Thread.new(socketServer.accept) do |connection|
puts "Accepting connection from: #{connection.peeraddr[2]}"
begin
while connection
incomingData = connection.gets("\0")
if incomingData != nil
incomingData = incomingData.chomp
end
puts "Incoming: #{incomingData}"
if incomingData == "DISCONNECT\0"
puts "Received: DISCONNECT, closed connection"
connection.close
break
else
connection.puts "#{incomingData}"
connection.flush
end
end
rescue Exception => e
# Displays Error Message
puts "#{ e } (#{ e.class })"
ensure
connection.close
puts "ensure: Closing"
end
end
end
I should give credit where due and the socket server code is based on this blog post: http://www.giantflyingsaucer.com/blog/?p=1147
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With