Module: ServerEngine::SocketManager

Defined in:
lib/serverengine/socket_manager.rb

Defined Under Namespace

Classes: Client, Server

Constant Summary collapse

INTERNAL_TOKEN =

This token is used for communication between peers. If token is mismatched, messages will be discarded

if ENV.has_key?('SERVERENGINE_SOCKETMANAGER_INTERNAL_TOKEN')
  ENV['SERVERENGINE_SOCKETMANAGER_INTERNAL_TOKEN']
else
  SecureRandom.hex
end

Class Method Summary collapse

Class Method Details

.recv_peer(peer) ⇒ Object



249
250
251
252
253
254
255
256
257
258
259
# File 'lib/serverengine/socket_manager.rb', line 249

def self.recv_peer(peer)
  res = peer.read(4)
  return nil if res.nil?

  len = res.unpack('N').first
  data = peer.read(len)
  data = JSON.parse(data)
  return nil if SocketManager::INTERNAL_TOKEN != data.first

  Marshal.load(Base64.strict_decode64(data.last))
end

.send_peer(peer, obj) ⇒ Object



242
243
244
245
246
247
# File 'lib/serverengine/socket_manager.rb', line 242

def self.send_peer(peer, obj)
  data = [SocketManager::INTERNAL_TOKEN, Base64.strict_encode64(Marshal.dump(obj))]
  data = JSON.generate(data)
  peer.write [data.bytesize].pack('N')
  peer.write data
end