开发者

ruby socket dgram example

开发者 https://www.devze.com 2022-12-28 04:28 出处:网络
I\'m trying to use unix sockets and SOCK_DGRAM in ruby, but am having a really hard time figuring out how to do it.So far, I\'ve been trying things like this:

I'm trying to use unix sockets and SOCK_DGRAM in ruby, but am having a really hard time figuring out how to do it. So far, I've been trying things like this:

sock_path = 'test.socket'
s1 = Socket.new(Socket::AF_UNIX, Socket::SOCK_DGRAM, 0)
s1.bind(Socket.pack_sockaddr_un(sock_path))

s2 = Socket.new(Socket::AF_UNIX, Socket::SOCK_DGRAM, 0)
s2.bind(Socke开发者_如何学Pythont.pack_sockaddr_un(sock_path))

s1.send("HELLO")
s2.recv(5) # should equal "HELLO"

Does anybody have experience with this?


In common case you need use connect and bind for both client and server sockets, so you need two different address for binding

require 'socket'

sock_path = 'test.socket'
sock_path2 = 'test2.socket'

s1 = Socket.new(Socket::AF_UNIX, Socket::SOCK_DGRAM, 0)
s1.bind(Socket.pack_sockaddr_un(sock_path))

s2 = Socket.new(Socket::AF_UNIX, Socket::SOCK_DGRAM, 0)
s2.bind(Socket.pack_sockaddr_un(sock_path2))
s2.connect(Socket.pack_sockaddr_un(sock_path))

s1.connect(Socket.pack_sockaddr_un(sock_path2))
s1.send("HELLO", 0)
puts s2.recv(5)

=> HELLO
0

精彩评论

暂无评论...
验证码 换一张
取 消