I want to create an application that sends and receives data parallel, like a chat application. It gets input and also sends some output, but NOT only if it receives data. I want to use UDP as protocol. I'm using ruby 1.9.3.
我想创建一个并行发送和接收数据的应用程序,比如聊天应用程序。它获取输入并发送一些输出,但不仅仅是它接收数据。我想使用UDP作为协议。我正在使用ruby 1.9.3。
here's the code that receives data:
这是接收数据的代码:
@s = UDPSocket.new
@s.bind(localhost, 1234)
Socket.udp_server_loop_on([@s]) do |message, sender|
#do something
end
This code should run independent from the rest of the application, it shouldn't block it.
此代码应独立于应用程序的其余部分运行,不应阻止它。
Should I use a thread? I've never tried a network program and I'm not a professional developer, so please be patient. Perhaps my code/design is just crap, so feel free to tell me how this is done by professionals! ;)
我应该使用线程吗?我从未尝试过网络程序而且我不是专业开发人员,所以请耐心等待。也许我的代码/设计只是垃圾,所以请随时告诉我这是由专业人士完成的! ;)
2 个解决方案
#1
2
UDP lends itself this sort of non-blocking processing quite naturally since you're receiving individual, atomic messages over your socket and can reply in the same fashion.
UDP很自然地适用于这种非阻塞处理,因为你通过套接字接收单独的原子消息并且可以以相同的方式回复。
Inside that loop, just be sure to process things quickly and send response messages. If you make long blocking calls it will hold up your loop and affect response times.
在该循环中,只需确保快速处理并发送响应消息。如果你进行长时间的阻塞调用,它将占用你的循环并影响响应时间。
EventMachine provides a structure for writing asynchronous applications and has its own methods for handling UDP and TCP sockets.
EventMachine提供了一种用于编写异步应用程序的结构,并且有自己的方法来处理UDP和TCP套接字。
Don't forget to look at solutions which are already implemented. For chat applications, Socket.IO is a great place to start.
不要忘记查看已经实施的解决方案。对于聊天应用程序,Socket.IO是一个很好的起点。
#2
1
You should take a look at Eventmachine
gem which handles blocking IO very efficiently. Among others it also offers TCP and UDP server/client API.
您应该看看Eventmachine gem,它可以非常有效地处理阻塞IO。其中它还提供TCP和UDP服务器/客户端API。
#1
2
UDP lends itself this sort of non-blocking processing quite naturally since you're receiving individual, atomic messages over your socket and can reply in the same fashion.
UDP很自然地适用于这种非阻塞处理,因为你通过套接字接收单独的原子消息并且可以以相同的方式回复。
Inside that loop, just be sure to process things quickly and send response messages. If you make long blocking calls it will hold up your loop and affect response times.
在该循环中,只需确保快速处理并发送响应消息。如果你进行长时间的阻塞调用,它将占用你的循环并影响响应时间。
EventMachine provides a structure for writing asynchronous applications and has its own methods for handling UDP and TCP sockets.
EventMachine提供了一种用于编写异步应用程序的结构,并且有自己的方法来处理UDP和TCP套接字。
Don't forget to look at solutions which are already implemented. For chat applications, Socket.IO is a great place to start.
不要忘记查看已经实施的解决方案。对于聊天应用程序,Socket.IO是一个很好的起点。
#2
1
You should take a look at Eventmachine
gem which handles blocking IO very efficiently. Among others it also offers TCP and UDP server/client API.
您应该看看Eventmachine gem,它可以非常有效地处理阻塞IO。其中它还提供TCP和UDP服务器/客户端API。