class

Socket

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

Constructors

new(family : Family, type : Type, protocol : Protocol = Protocol::IP, blocking = nil)

Creates a socket. Consider using TCPSocket, TCPServer, UDPSocket, UNIXSocket or UNIXServer unless you need full control over the socket.

Source
new(fd, family : Family, type : Type, protocol : Protocol = Protocol::IP, blocking = nil)

Creates a Socket 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
tcp(family : Family, blocking = nil) : self

Creates a TCP socket. Consider using TCPSocket or TCPServer unless you need full control over the socket.

Source
udp(family : Family, blocking = nil) : self

Creates an UDP socket. Consider using UDPSocket unless you need full control over the socket.

Source
unix(type : Type = Type::STREAM, blocking = nil) : self

Creates an UNIX socket. Consider using UNIXSocket or UNIXServer unless you need full control over the socket.

Source

Class methods

fcntl(fd, cmd, arg = 0)
Source
get_blocking(fd : Handle) : Bool

Returns whether the blocking mode of fd is blocking (true) or non blocking (false).

NOTE: Only implemented on UNIX targets. Raises on Windows.

Source
ip?(string : String)

Returns true if the string represents a valid IPv4 or IPv6 address.

Source
set_blocking(fd : Handle, value : Bool)

Changes the blocking mode of fd to be blocking (true) or non blocking (false).

Source

Instance methods

accept

Accepts an incoming connection.

Returns the client socket. Raises an IO::Error (closed stream) exception if the server is closed after invoking this method.

require "socket"

server = TCPServer.new(2202)
socket = server.accept
socket.puts Time.utc
socket.close
Source
accept?

Accepts an incoming connection.

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

require "socket"

server = TCPServer.new(2202)
if socket = server.accept?
  socket.puts Time.utc
  socket.close
end
Source
bind(host : String, port : Int) : Nil

Binds the socket to a local address.

require "socket"

sock = Socket.tcp(Socket::Family::INET)
sock.bind "localhost", 1234
Source
bind(port : Int)

Binds the socket on port to all local interfaces.

require "socket"

sock = Socket.tcp(Socket::Family::INET6)
sock.bind 1234
Source
bind(addr : Socket::Address) : Nil

Binds the socket to a local address.

require "socket"

sock = Socket.udp(Socket::Family::INET)
sock.bind Socket::IPAddress.new("192.168.1.25", 80)
Source
blocking

Returns whether the socket's mode is blocking (true) or non blocking (false).

Source
blocking=(value)

Changes the socket's mode to blocking (true) or non blocking (false).

WARNING: The socket has been configured to behave correctly with the event loop runtime requirements. Changing the blocking mode can cause the event loop to misbehave, for example block the entire program when a fiber tries to read from this socket.

Source
broadcast=(val : Bool)
Source
broadcast?
Source
close_on_exec=(arg : Bool)
Source
close_on_exec?
Source
close_read

Calls shutdown(2) with SHUT_RD

Source
close_write

Calls shutdown(2) with SHUT_WR

Source
closed?

Returns true if this IO is closed.

IO defines returns false, but including types may override.

Source
connect(host : String, port : Int, connect_timeout = nil) : Nil

Connects the socket to a remote host:port.

require "socket"

sock = Socket.tcp(Socket::Family::INET)
sock.connect "crystal-lang.org", 80
Source
connect(addr, timeout = nil) : Nil

Connects the socket to a remote address. Raises if the connection failed.

require "socket"

sock = Socket.unix
sock.connect Socket::UNIXAddress.new("/tmp/service.sock")
Source
connect(addr, timeout = nil, &)

Tries to connect to a remote address. Yields an IO::TimeoutError or an Socket::ConnectError error if the connection failed.

Source
family
Source
fcntl(cmd, arg = 0)
Source
fd

Returns the handle associated with this socket from the operating system.

  • on POSIX platforms, this is a file descriptor (Int32)
  • on Windows, this is a SOCKET handle (LibC::SOCKET)

The returned system socket has been configured as per the IO system runtime requirements. If the returned socket must be in a specific mode or have a specific set of flags set, then they must be applied, even when it feels redundant, because even the same target isn't guaranteed to have the same requirements at runtime.

Source
finalize

Finalizes the socket resource.

This involves releasing the handle to the operating system, i.e. closing it. It does not implicitly call #flush, so data waiting in the buffer may be lost. By default write buffering is disabled, though (sync? == true). It's recommended to always close the socket explicitly via #close.

This method is a no-op if the file descriptor has already been closed.

Source
inspect(io : IO) : Nil

Appends a String representation of this object which includes its class name, its object address and the values of all instance variables.

class Person
  def initialize(@name : String, @age : Int32)
  end
end

Person.new("John", 32).inspect # => #<Person:0x10fd31f20 @name="John", @age=32>
Source
keepalive=(val : Bool)
Source
keepalive?
Source
linger
Source
linger=(val : Int | Nil)

WARNING: The behavior of SO_LINGER is platform specific. Bad things may happen especially with nonblocking sockets. See Cross-Platform Testing of SO_LINGER by Nybek for more information.

  • nil: disable SO_LINGER
  • Int: enable SO_LINGER and set timeout to Int seconds
    • 0: abort on close (socket buffer is discarded and RST sent to peer). Depends on platform and whether shutdown() was called first.
    • >=1: abort after Int seconds on close. Linux and Cygwin may block on close.
Source
listen(backlog : Int = SOMAXCONN) : Nil

Tells the previously bound socket to listen for incoming connections.

Source
listen(backlog : Int = SOMAXCONN, &)

Tries to listen for connections on the previously bound socket. Yields an Socket::Error on failure.

Source
protocol
Source
read_timeout

The time to wait when reading before raising an IO::TimeoutError.

Source
read_timeout=(read_timeout : Time::Span | Nil)

The time to wait when reading before raising an IO::TimeoutError.

Source
read_timeout=(read_timeout : Number) : Number

Sets the number of seconds to wait when reading before raising an IO::TimeoutError.

Source
receive(message : Bytes) : Tuple(Int32, Address)

Receives a binary message from the previously bound address.

require "socket"

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

message = Bytes.new(32)
bytes_read, client_addr = server.receive(message)
Source
receive(max_message_size = 512) : Tuple(String, Address)

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
recv_buffer_size
Source
recv_buffer_size=(val : Int32)
Source
reuse_address=(val : Bool)
Source
reuse_address?
Source
reuse_port=(val : Bool)
Source
reuse_port?
Source
send(message, to addr : Address) : Int32

Sends a message to the specified remote address. Returns the number of bytes sent. Does not guarantee that the entire message is sent. That's only the case when the return value is equivalent to message.bytesize. #write ensures the entire message is sent but it requires an established connection.

require "socket"

server = Socket::IPAddress.new("10.0.3.1", 2022)
sock = Socket.udp(Socket::Family::INET)
sock.connect("example.com", 2000)
sock.send("text query", to: server)
Source
send(message) : Int32

Sends a message to a previously connected remote address. Returns the number of bytes sent. Does not guarantee that the entire message is sent. That's only the case when the return value is equivalent to message.bytesize. #write ensures the entire message is sent.

require "socket"

sock = Socket.udp(Socket::Family::INET)
sock.connect("example.com", 2000)
sock.send("text message")

sock = Socket.unix(Socket::Type::DGRAM)
sock.connect Socket::UNIXAddress.new("/tmp/service.sock")
sock.send(Bytes[0])
Source
send_buffer_size
Source
send_buffer_size=(val : Int32)
Source
sendfile(file : IO::FileDescriptor, offset : Int, count : Int) : Int64

Writes count bytes from file to socket starting from the byte at offset, avoiding to copy data between the kernel and user spaces (zero- copy).

Returns how many bytes have actually been written. This should always be count but may be less, for example if offset + count is greater than the file size.

Doesn't directly read from file so the current file position (IO#pos) doesn't change.

For example, to send an entire file minus the first 44 bytes:

require "socket"

sock = Socket.tcp(Socket::Family::INET)
sock.connect("localhost", 1234)

File.open("audio.wav") do |file|
  sock.sendfile(file, 44, file.info.size - 44)
  file.pos # => 0
end

The method leverages the sendfile (UNIX) and TransmitFile (Windows) syscalls when available for the copy to happen entirely in the kernel. The feature is emulated in user space on other targets.

@[Experimental]

Source
tty?

Returns true if this IO is associated with a terminal device (tty), false otherwise.

IO returns false, but including types may override.

STDIN.tty?          # => true
IO::Memory.new.tty? # => false
Source
type
Source
write_timeout

Sets the time to wait when writing before raising an IO::TimeoutError.

Source
write_timeout=(write_timeout : Time::Span | Nil)

Sets the time to wait when writing before raising an IO::TimeoutError.

Source
write_timeout=(write_timeout : Number) : Number

Sets the number of seconds to wait when writing before raising an IO::TimeoutError.

Source

Nested types