# Socket hang in thread

**URL:** <https://www.ruby-forum.com/t/socket-hang-in-thread/175578>\
**Category:** Ruby\
**Created:** [September 15, 2009, 11:10pm UTC](https://www.ruby-forum.com/t/socket-hang-in-thread/175578 "2009-09-15T23:10:57Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![oliver-peng](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/o/b3f665/32.png) [@oliver-peng](https://www.ruby-forum.com/u/oliver-peng)\
**Post date:** [September 15, 2009, 11:10pm UTC](https://www.ruby-forum.com/t/socket-hang-in-thread/175578/1 "2009-09-15T23:10:57Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![oliver-peng](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/o/b3f665/32.png) [@oliver-peng](https://www.ruby-forum.com/u/oliver-peng)\
**Post date:** [September 16, 2009, 9:49pm UTC](https://www.ruby-forum.com/t/socket-hang-in-thread/175578/2 "2009-09-16T21:49:03Z")

</div>

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
