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
精彩评论