Socket hang in thread

O

Oliver Peng

Design a thread and in the thread start a new TCPServer and get income
string.

Start irb in Windows cmd:

irb(main):001:0> require 'socket'
=> true
irb(main):002:0>
irb(main):003:0* class TestServe < Thread
irb(main):004:1>
irb(main):005:1* def initialize(host, port)
irb(main):006:2>
irb(main):007:2* @tcpServer = TCPServer.new(host, port)
irb(main):008:2> @tcpServer.listen(25)
irb(main):009:2>
irb(main):010:2* super {
irb(main):011:3* begin
irb(main):012:4* if tcp = @tcpServer.accept
irb(main):013:5>
irb(main):014:5* while line = tcp.gets()
irb(main):015:6> puts line
irb(main):016:6> tcp.write(line)
irb(main):017:6> end
irb(main):018:5> end
irb(main):019:4> rescue SignalException, StandardError => e
irb(main):020:4> puts("%s exception %s:\n%s" % [self.class,
e.inspect
, e.backtrace.join("\n")])
irb(main):021:4> end
irb(main):022:3> }
irb(main):023:2> end
irb(main):024:1> end
=> nil
irb(main):025:0>
irb(main):026:0*
irb(main):027:0* server = TestServe.new('127.0.0.1', 12345)
=> #<TestServe:0x1019a700 sleep>
irb(main):028:0>

I open another Windows cmd window and try to use telnet to connect to
same address and port. The problem is all chars I input in telnet
doesn't show in irb until I go back to irb window and hit return button.

So it looks that in thread the server socket was blocked.

I also tried to start irb and run same code in the Cygwin cmd
enviroment. Once I input anything in telnet, I can see it in irb.

Any suggestions?

Thanks.
 
M

Michael Linfield

Use a buffer in your code.

@@username = "user";
@@buffer = []

def server(io)

loop do
if IO.select([io], nil, nil, 2)
line = io.gets
end

@@buffer << [@@username,line]

b_size = @@buffer.size

@@buffer[b_size..-1].each_with_index do |line, index|
io.puts("#{line[0]} says: #{line[1]}")
end
end

Regards,

- Mac
 

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,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top