Socket
Inherits Crystal::System::Socket / IO::Buffered / IO / Reference / Object
Constructors
Creates a socket. Consider using TCPSocket, TCPServer, UDPSocket,
UNIXSocket or UNIXServer unless you need full control over the socket.
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.
Creates a TCP socket. Consider using TCPSocket or TCPServer unless you
need full control over the socket.
Creates an UDP socket. Consider using UDPSocket unless you need full
control over the socket.
Creates an UNIX socket. Consider using UNIXSocket or UNIXServer unless
you need full control over the socket.
Class methods
Returns whether the blocking mode of fd is blocking (true) or non blocking (false).
NOTE: Only implemented on UNIX targets. Raises on Windows.
Instance methods
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
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
Binds the socket to a local address.
require "socket"
sock = Socket.tcp(Socket::Family::INET)
sock.bind "localhost", 1234
Binds the socket on port to all local interfaces.
require "socket"
sock = Socket.tcp(Socket::Family::INET6)
sock.bind 1234
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)
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.
Returns true if this IO is closed.
IO defines returns false, but including types may override.
Connects the socket to a remote host:port.
require "socket"
sock = Socket.tcp(Socket::Family::INET)
sock.connect "crystal-lang.org", 80
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")
Tries to connect to a remote address. Yields an IO::TimeoutError or an
Socket::ConnectError error if the connection failed.
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.
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.
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>
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: disableSO_LINGERInt: enableSO_LINGERand set timeout toIntseconds0: abort on close (socket buffer is discarded and RST sent to peer). Depends on platform and whethershutdown()was called first.>=1: abort afterIntseconds on close. Linux and Cygwin may block on close.
Tells the previously bound socket to listen for incoming connections.
Tries to listen for connections on the previously bound socket.
Yields an Socket::Error on failure.
The time to wait when reading before raising an IO::TimeoutError.
Sets the number of seconds to wait when reading before raising an IO::TimeoutError.
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)
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
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)
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])
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]
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
Sets the time to wait when writing before raising an IO::TimeoutError.