# Problem with reading from socket

**URL:** <https://www.ruby-forum.com/t/problem-with-reading-from-socket/67499>\
**Category:** Ruby\
**Created:** [September 4, 2006, 5:33pm UTC](https://www.ruby-forum.com/t/problem-with-reading-from-socket/67499 "2006-09-04T17:33:45Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Hemant\_S](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/8797f3/32.png) [@Hemant\_S](https://www.ruby-forum.com/u/Hemant_S)\
**Post date:** [September 4, 2006, 5:33pm UTC](https://www.ruby-forum.com/t/problem-with-reading-from-socket/67499/1 "2006-09-04T17:33:45Z")

</div>

I have a issue in reading from Sockets(both TCPSockets and  
UNIXSockets).the  
problem is with following code snippets:

```
begin

```

> ```
> timeout(8) do
> ret_data = @proxy_con.gets()
> end
> rescue Timeout::Error
> return nil
> rescue Exception => e
> return nil
> end
> 
> ```

The problem is, since read(or gets) from socket blocks the thread(or  
process), i do a timeout on it.and return nil to the client.Now the next  
time, the client puts some request, i put it to the socket and do a  
gets. So  
what happens is I get data for the previous request, because i guess the  
socket buffer was not cleared up( or whatever name people use for this).

Can i use noblock on TCPSockets/UNIXSockets?

I guess, its a pretty basic problem, but how do i go about solving this?

---

<div class="post-metadata">

**Author:** ![Hemant\_S](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/8797f3/32.png) [@Hemant\_S](https://www.ruby-forum.com/u/Hemant_S)\
**Post date:** [September 4, 2006, 5:45pm UTC](https://www.ruby-forum.com/t/problem-with-reading-from-socket/67499/2 "2006-09-04T17:45:46Z")

</div>

On 9/4/06, Hemant . [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> > ```
> > return nil
> > 
> > ```
> 
> what happens is I get data for the previous request, because i guess the  
> socket buffer was not cleared up( or whatever name people use for this).
> 
> Can i use noblock on TCPSockets/UNIXSockets?
> 
> I guess, its a pretty basic problem, but how do i go about solving this?

You can use nonblocking I/O on both TCP sockets and Unix-domain sockets.  
Improved nbio APIs were added late last May and are in the current  
snaps.  
Obviously you have to use all the standard techniques for nbio. As a  
possible alternative, look at the EventMachine library.
