Socket.io
Socket.io c++ client 사용하기
web server에서 linux daemon과 windows application(C#)으로 이벤트를 보내야하는 상황으로 양방향 메시지 송수신이 필요했다.
이를 위해 사용한 것이..
우선 SioChatDemo 예제를 기반으로 socket.io c++ client 라이브러리를 만들고 이를 기반으로 웹서버로부터 이벤트를 수신할 수 있는 어플리케이션을 개발했다.
- Windows : SioChatDemo.sln
- Linux : cmake 사용
$ cmake ./ $ make install
각각 빌드를 하면 socket.io c++ client 기능의 메인이 되는 라이브러리(linux: libsioclient.a, libsioclient_tls.a)
가 빌드된다.
socket.io c++ client의 중요 API를 간략하게 설명하자면 아래와 같다…
server 연결
sio::client h;
h.connect("http://127.0.0.1:3000"); // socket.io server
event 발생
나는 간단한 이벤트만 보내서 string 정도만 함께 보냈지만 message::list를 이용하면 리스트형태의 파라미터도 전달가능한듯(sio_message.h
에서 보면 내부에서 vector로 구현되어 있음)
// emit event name only:
h.socket()->emit("login");
// emit text
h.socket()->emit("add user", username);
// emit binary
char buf[100];
h.socket()->emit("add user", std::make_shared<std::string>(buf,100));
// emit message object with lambda ack handler
h.socket()->emit("add user", string_message::create(username), [&](message::list const& msg) {
});
// emit multiple arguments
message::list li("sports");
li.push(string_message::create("economics"));
socket->emit("categories", li);
event를 수신할 수 있는 callback 함수 연결
아래와 같이 socket.io server(JS)에서 socket.on()
로 발생시킨 이벤트를 수신했을 때 수행할 함수를 등록시킬 수 있다.
function pointer 전달해서 등록시킬 수도 있고…
void OnMessage(sio::event &) {
// blah blah
}
h.socket()->on("new message", &OnMessage);
편리하게 lambda식으로 등록시킬 수도 있다.
h.socket()->on("login", [&](sio::event& ev)
{
//handle login message
//post to UI thread if any UI updating.
});