Recommanded Free YOUTUBE Lecture: <% selectedImage[1] %>

Contents

Gserver

여자처자 해서 간만에 서버 프로그램을 만들어야 했다. 예전 같으면 C나 C++로 만들었을테지만, 요즘엔 귀찮다. 왠만하면 HTTP 기반으로 하고 있는데, 이번엔 HTTP를 쓸 수 있는 상황이 아니다. Persistant한 통신채널을 유지해야 하기 때문이다.

최근 ruby 언어를 사용하고 있으니, ruby기반으로 서버 프로그램을 간단히 만들 수 있는 무언가 있을 거라고생각해서 찾은게 "GServer"이다.

GServer는 thread pool관리, 로깅, 멀티 스레드 관리와 같은 기능을 내장하고 있는 루비 라이브러리다.

Hello 서버 프로그램

Hello World를 출력하는 소켓 프로그램을 만들었다.
#!/usr/bin/ruby

require 'gserver'

class TestServer < GServer
  def initialize(port=8000, *args)
    super(port, *args)
  end
  def serve(io)
    io.puts "What is your name?"
    name = io.gets
    io.puts "Hello #{name}"
    server.stop
  end
end

server = TestServer.new
server.audit = true
server.start

server.join
아 간단하다. 이걸로 멀티 스레드 기반의 Hello 서버 프로그램을 만들었다.

상수

DEFAULT_HOST

기본 bind 호스트 주소로 "127.0.0.1"이다. 위 예제는 bind 호스트를 설정하지 않았으므로, DEFAULT_HOST가 설정된다. netstate로 확인해 보자.
# netstat -na | grep 8000
tcp        0      0 127.0.0.1:8000          0.0.0.0:*               LISTEN     
인터넷에서 연결할 수 있도록 bind 주소를 변경하고 싶다면, host attribute를 이용해서 bind 호스트를 설정해야 한다.
  def initialize(port=8000, host="0.0.0.0", *args)
    super(port, host, *args)
  end

Attribute

==== audit === true로 설정하면 서버작동 중에 발생하는 connecting, disconnecting, starting, stopping 이벤트의 발생을 알려준다.
[Mon Jul  8 23:04:02 2013] TestServer 127.0.0.1:8000 start
[Mon Jul  8 23:04:13 2013] TestServer 127.0.0.1:8000 client:48277 127.0.0.1<127.0.0.1> connect
[Mon Jul  8 23:04:16 2013] TestServer 127.0.0.1:8000 client:48277 disconnect

debug

true로 설정하면 자세한 로그 정보를 보여준다.

host

Bind할 호스트의 주소

port

Listen 포트번호

stdlog

public instnce methods

connections

현재 연결된 클라이언트 개수를 반환한다.

join

서버 thread를 join 한다.

start(maxConnections = -1)

서버를 시작한다. maxConnections는 동시 연결을 허용할 최대 클라이언트 수다.

stop

서버 연결을 종료한다.

stopped?

서버 연결이 종료됐다면 true 를 반환한다.

Protected Instance method

connection(client)

disconnectiong(clientPort)

error(detail)

log(msg)

starting()

stopping()