Class: SFML::Network::TcpListener

Inherits:
Object
  • Object
show all
Defined in:
lib/sfml/network/tcp_listener.rb

Overview

The server side of TCP. Listens on a port; #accept blocks until a client connects, then returns a fresh TcpSocket for that peer.

listener = SFML::Network::TcpListener.new
listener.listen(port: 8080)
loop do
status, peer = listener.accept
break unless status == :done
handle_client(peer)
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize ⇒ TcpListener

Returns a new instance of TcpListener.

Raises:



14
15
16
17
18
# File 'lib/sfml/network/tcp_listener.rb', line 14

def initialize
  ptr = C::Network.sfTcpListener_create
  raise NetworkError, "sfTcpListener_create returned NULL" if ptr.null?
  @handle = FFI::AutoPointer.new(ptr, C::Network.method(:sfTcpListener_destroy))
end

Instance Attribute Details

#handle ⇒ Object (readonly)

:nodoc:



62
63
64
# File 'lib/sfml/network/tcp_listener.rb', line 62

def handle
  @handle
end

Instance Method Details

#accept ⇒ Object

Returns [status, TcpSocket] — the socket is non-nil only when status == :done.



37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/sfml/network/tcp_listener.rb', line 37

def accept
  out_ptr = FFI::MemoryPointer.new(:pointer)
  code = C::Network.sfTcpListener_accept(@handle, out_ptr)
  status = C::Network::STATUSES[code]

  return [status, nil] unless status == :done
  sock_ptr = out_ptr.read_pointer
  return [status, nil] if sock_ptr.null?

  sock = TcpSocket.allocate
  sock.instance_variable_set(:@handle, FFI::AutoPointer.new(sock_ptr, C::Network.method(:sfTcpSocket_destroy)))
  [status, sock]
end

#blocking=(value) ⇒ Object

Set the blocking.



55
56
57
# File 'lib/sfml/network/tcp_listener.rb', line 55

def blocking=(value)
  C::Network.sfTcpListener_setBlocking(@handle, value ? true : false)
end

#blocking? ⇒ Boolean

true if blocking.

Returns:

  • (Boolean)


52
# File 'lib/sfml/network/tcp_listener.rb', line 52

def blocking? = C::Network.sfTcpListener_isBlocking(@handle)

#close ⇒ Object

Returns the close.



30
31
32
33
# File 'lib/sfml/network/tcp_listener.rb', line 30

def close
  C::Network.sfTcpListener_close(@handle)
  self
end

#listen(port:, address: IpAddress::ANY) ⇒ Object

Bind the listener to a port and start listening. address (default: any local interface) restricts which interface to listen on — pass IpAddress::LOCALHOST for loopback-only.



23
24
25
26
27
# File 'lib/sfml/network/tcp_listener.rb', line 23

def listen(port:, address: IpAddress::ANY)
  addr = address.is_a?(IpAddress) ? address : IpAddress.from_string(address)
  code = C::Network.sfTcpListener_listen(@handle, Integer(port), addr.struct)
  C::Network::STATUSES[code]
end

#local_port ⇒ Object

Returns the local port.



60
# File 'lib/sfml/network/tcp_listener.rb', line 60

def local_port = C::Network.sfTcpListener_getLocalPort(@handle)