Class: Cod::TcpServer

Inherits:
Object
  • Object
show all
Defined in:
lib/cod/tcp_server.rb

Overview

A tcp server channel. Messages are read from any of the connected sockets in a round robin fashion.

Synopsis:

server = Cod.tcp_server('localhost:12345') 
server.get  # 'a message'
msg, chan = server.get_ext

There is no implementation of #put that would broadcast back to all connected sockets, this is up to you to implement. Instead, you can use one of two ways to obtain a channel for talking back to a specific client:

Using #get_ext:

msg, chan = server.get_ext

chan is a two way connected channel to the specific client that has opened its communication with msg.

Using plain #get:

# on the client: 
client.put [client, :msg]
# on the server
chan, msg = server.get

This means that you can transmit the client channel through the connection as part of the message you send.

Instance Method Summary collapse

Constructor Details

#initialize(bind_to) ⇒ TcpServer

Returns a new instance of TcpServer.



32
33
34
35
36
37
38
# File 'lib/cod/tcp_server.rb', line 32

def initialize(bind_to)
  @socket = TCPServer.new(*bind_to.split(':'))
  @client_sockets = []
  @round_robin_index = 0
  @messages = Array.new
  @serializer = SimpleSerializer.new
end

Instance Method Details

#client(answers_to) ⇒ Object

NOTE: It is really more convenient to just construct a Cod.tcp_client and ask that for a client object. In the case of TCP, this is enough.



95
96
97
# File 'lib/cod/tcp_server.rb', line 95

def client(answers_to)
  Service::Client.new(answers_to, answers_to)
end

#closeObject

Closes the channel.



69
70
71
72
# File 'lib/cod/tcp_server.rb', line 69

def close
  @socket.close
  @client_sockets.each { |io| io.close }
end

#connectionsObject

Returns the number of clients that are connected to this server currently.



83
84
85
# File 'lib/cod/tcp_server.rb', line 83

def connections
  @client_sockets.size
end

#get(opts = {}) ⇒ Object

Receives one object from the channel.

Example:

channel.get # => object


45
46
47
48
# File 'lib/cod/tcp_server.rb', line 45

def get(opts={})
  msg, socket = _get(opts)
  return msg
end

#get_ext(opts = {}) ⇒ Object

Receives one object from the channel. Returns a tuple of <message,channel> where channel is a tcp channel that links back to the client that sent message.

Using this method, the server can communicate back to its clients individually instead of collectively.

Example:

msg, chan = server.get_ext
chan.put :answer


60
61
62
63
64
65
# File 'lib/cod/tcp_server.rb', line 60

def get_ext(opts={})
  msg, socket = _get(opts)
  return [
    msg, 
    TcpClient.new(socket, @serializer)]
end

#serviceObject

——————————————————— service/client



89
90
91
# File 'lib/cod/tcp_server.rb', line 89

def service
  Service.new(self)
end

#to_read_fdsObject

Returns an array of IOs that Cod.select should select on.



76
77
78
# File 'lib/cod/tcp_server.rb', line 76

def to_read_fds
  @client_sockets
end