class

UNIXSocket

Inherits Socket / Crystal::System::Socket / IO::Buffered / IO / Reference / Object

A local interprocess communication clientsocket.

Available on UNIX-like operating systems, and Windows 10 Build 17063 or above. Not all features are supported on Windows.

NOTE: To use UNIXSocket, you must explicitly import it with require "socket"

Example usage:

require "socket"

sock = UNIXSocket.new("/tmp/myapp.sock")
sock.puts "message"
response = sock.gets
sock.close

Constructors

new(path : Path | String, type : Type = Type::STREAM)

Connects a named UNIX socket, bound to a filesystem pathname.

Source
new(*, fd : Handle, type : Type = Type::STREAM, path : Path | String | Nil = nil)

Creates an UNIXSocket from an existing system file descriptor or socket handle.

This adopts the system socket into the IO system that will reconfigure it as per the event loop runtime requirements.

NOTE: On Windows, the handle must have been created with WSA_FLAG_OVERLAPPED.

Source

Class methods

open(path : Path | String, type : Type = Type::STREAM, &)

Opens an UNIX socket to a filesystem pathname, yields it to the block, then eventually closes the socket when the block returns.

Returns the value of the block.

Source
pair(type : Type = Type::STREAM) : Tuple(UNIXSocket, UNIXSocket)

Returns a pair of unnamed UNIX sockets.

Not supported on Windows.

require "socket"

left, right = UNIXSocket.pair

spawn do
  # echo server
  message = right.gets
  right.puts message
end

left.puts "message"
left.gets # => "message"
Source
pair(type : Type = Type::STREAM, &)

Creates a pair of unnamed UNIX sockets (see pair) and yields them to the block. Eventually closes both sockets when the block returns.

Returns the value of the block.

Not supported on Windows.

Source

Instance methods

local_address
Source
path
Source
receive(max_message_size = 512) : Tuple(String, UNIXAddress)

Receives a text message from the previously bound address.

require "socket"

server = Socket.udp(Socket::Family::INET)
server.bind("localhost", 1234)

message, client_addr = server.receive
Source
remote_address
Source