2010-04-27 52 views
1

我想在ruby中使用unix套接字和SOCK_DGRAM,但是我很難搞清楚如何去做。到目前爲止,我一直在嘗試這樣的事情:紅寶石套接字dgram示例

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(Socket.pack_sockaddr_un(sock_path)) 

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

有沒有人有這方面的經驗?

回答

2

在你需要使用的客戶端和服務器套接字connectbind常見的情況,所以你需要兩個不同的地址綁定

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