简体   繁体   中英

Persistent TCPSocket and Ruby threads

I am connecting to a server as a client using TCPSocket. The main point is to keep connection open and send there or receive from there messages as soon as they arrive.

There are no problems with sending messages, but doing socket.recv(n) in main thread when server has nothing to respond with, makes client's main thread to pause while waiting for data.

What is the good practice to work with persistent connections in Ruby to prevent main thread blocking?

Let's suppose that extra thread should be used. Where to insert this thread initialization in Rails app? Make a worker process?

Receiving data on a dedicated thread is certainly possible. But also consider using IO#select or IO#read_nonblock . ( TCPSocket is a subclass of IO .) If you are waiting for data to come from any one of several sockets, IO#select would be ideal. If you are doing some other processing on the main thread, but also need to remain responsive to input coming in from a socket, you can call IO#read_nonblock at intervals.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM