Thread Questions

M

Max Kuffs

Hello,

I would like to write a little TCPServer which communicates with
another ruby program on another computer.

So i tried all with TCPServer. I could connect and it worked, but i
want to execute it in a thread and now the program halts when i open
the server.


i use ruby 1.8 for windows. does this matter in that case?

best regards
Max Kuffs

My source:

require 'socket'

SERVER_PORT = 4772
LISTEN_ON = '0.0.0.0'

srv = Thread.new(){
ss=TCPServer.new LISTEN_ON,SERVER_PORT
con=ss.accept
while !con.eof?
puts con.gets
end
}

while true do
puts "Cycle"
if srv.stop? then
# Restarting Thread if died
puts "Restarting Server Thread!"
srv.run
end
puts "sleeep-----------------------------------------"
sleep 5

end
 
R

Robert Klemme

Max Kuffs said:
Hello,

I would like to write a little TCPServer which communicates with
another ruby program on another computer.

So i tried all with TCPServer. I could connect and it worked, but i
want to execute it in a thread and now the program halts when i open
the server.

You got the logic wrong: typically you want to serve each client in a
separate thread. Try this:

require 'socket'

SERVER_PORT = 4772
LISTEN_ON = '0.0.0.0'

server = TCPServer.new LISTEN_ON, SERVER_PORT
clients = 0

while true
Thread.new( server.accept, clients += 1 ) do |con, clnt|
puts "Connect with client #{clnt}"
while ( line = ( con.gets ) )
puts "From client #{clnt}: #{line}"
end
puts "EOF #{clnt}"
end
end

Note: I introduced "clients" and "clnt" just for the purpose of
distinguishing output from different clients.

Kind regards

robert
 
M

Max Kuffs

thank you very much!
the example helped, i think i understand why it didn't work the way i
wanted.

regards
max kuffs
 

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
474,431
Messages
2,571,678
Members
48,796
Latest member
Greg L.

Latest Threads

Top