Establishing new TCP Socket connection

J

Joe Van Dyk

Hi,

If I want to establish a new TCP connection every time I need to
access data (the server doesn't want to keep old connetions around),
is there any reason why I can't do something like:

def send_message_and_recv_response
server =3D TCPSocket.new @server_ip, @server_port
server.puts "the message"
result =3D server.recv
end
 
E

Eric Hodel

If I want to establish a new TCP connection every time I need to
access data (the server doesn't want to keep old connetions around),
is there any reason why I can't do something like:

def send_message_and_recv_response
server = TCPSocket.new @server_ip, @server_port
server.puts "the message"
result = server.recv
end

You could be more friendly to the other end by adding an explicit close:

def do_the_stuff
sock = TCPSocket.new @ip, @port
sock.puts "message"
return sock.recv
ensure
sock.close unless sock.nil?
end
 
A

Adam P. Jenkins

Joe said:
Hi,

If I want to establish a new TCP connection every time I need to
access data (the server doesn't want to keep old connetions around),
is there any reason why I can't do something like:

def send_message_and_recv_response
server = TCPSocket.new @server_ip, @server_port
server.puts "the message"
result = server.recv
end

Sure, except you should explicitly close the connection as well at the
end of your block rather than letting the socket object's finalizer do
it whenever the GC gets around to calling it. So, something like:

def send_message_and_recv_response
server = nil
server = TCPSocket.new @server_ip, @server_port
server.puts "the message"
result = server.recv
ensure
server.close if server
end
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top