class SF::TcpListener

Overview

Socket that listens to new TCP connections

A listener socket is a special type of socket that listens to a given port and waits for connections on that port. This is all it can do.

When a new connection is received, you must call accept and the listener returns a new instance of SF::TcpSocket that is properly initialized and can be used to communicate with the new client.

Listener sockets are specific to the TCP protocol, UDP sockets are connectionless and can therefore communicate directly. As a consequence, a listener socket will always return the new connections as SF::TcpSocket instances.

A listener is automatically closed on destruction, like all other types of socket. However if you want to stop listening before the socket is destroyed, you can call its #close() function.

Usage example:

# Create a listener socket and make it wait for new
# connections on port 55001
listener = SF::TcpListener.new
listener.listen(55001)

# Endless loop that waits for new connections
while running
  client = SF::TcpSocket.new
  if listener.accept(client) == SF::Socket::Done
    # A new client just connected!
    puts "New connection received from #{client.remote_address}"
    do_something_with client
  end
end

See also: SF::TcpSocket, SF::Socket

Defined in:

network/obj.cr

Constructors

Instance Method Summary

Instance methods inherited from class SF::Socket

blocking=(blocking : Bool) blocking=, blocking? : Bool blocking?, finalize finalize

Constructor Detail

def self.new #

Default constructor


[View source]

Instance Method Detail

def accept(socket : TcpSocket) : Socket::Status #

Accept a new connection

If the socket is in blocking mode, this function will not return until a connection is actually received.

  • socket - Socket that will hold the new connection

Returns: Status code

See also: #listen


[View source]
def close #

Stop listening and close the socket

This function gracefully stops the listener. If the socket is not listening, this function has no effect.

See also: #listen


[View source]
def finalize #
Description copied from class SF::Socket

Destructor


[View source]
def listen(port : Int, address : IpAddress = IpAddress::Any) : Socket::Status #

Start listening for incoming connection attempts

This function makes the socket start listening on the specified port, waiting for incoming connection attempts.

If the socket is already listening on a port when this function is called, it will stop listening on the old port before starting to listen on the new port.

  • port - Port to listen on for incoming connection attempts
  • address - Address of the interface to listen on

Returns: Status code

See also: #accept, #close


[View source]
def local_port : UInt16 #

Get the port to which the socket is bound locally

If the socket is not listening to a port, this function returns 0.

Returns: Port to which the socket is bound

See also: #listen


[View source]