class

UNIXServer

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

A local interprocess communication server socket.

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

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

Example usage:

require "socket"

def handle_client(client)
  message = client.gets
  client.puts message
end

server = UNIXServer.new("/tmp/myapp.sock")
while client = server.accept?
  spawn handle_client(client)
end

Constructors

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

Creates a named UNIX socket, listening on a filesystem pathname.

Always deletes any existing filesystem pathname first, in order to cleanup any leftover socket file.

The server is of stream type by default, but this can be changed for another type. For example datagram messages:

UNIXServer.new("/tmp/dgram.sock", Socket::Type::DGRAM)

Only the stream type is supported on Windows.

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

Creates a UNIXServer from an existing system file descriptor or socket handle.

This adopts fd 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, backlog = 128, &)

Creates a new UNIX server and yields it to the block. Eventually closes the server socket when the block returns.

Returns the value of the block.

Source

Instance methods

accept?

Accepts an incoming connection.

Returns the client socket or nil if the server is closed after invoking this method.

Source
close(delete = true) : Nil

Closes the socket, then deletes the filesystem pathname if it exists.

Source