Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

使用 nev 库实现一个简单的 echo 服务 #1

Open
hilarryxu opened this issue Dec 2, 2020 · 0 comments
Open

使用 nev 库实现一个简单的 echo 服务 #1

hilarryxu opened this issue Dec 2, 2020 · 0 comments
Labels
Doc 教程文档

Comments

@hilarryxu
Copy link
Owner

hilarryxu commented Dec 2, 2020

当整个网络库写完后,最终实现一个简单的 echo 服务示例代码如下:

#include <stdio.h>

#include <string>

#include "nev/nev_init.h"
#include "nev/ip_endpoint.h"
#include "nev/event_loop.h"
#include "nev/tcp_server.h"

using namespace nev;

void onConnection(const TcpConnectionSharedPtr& conn) {
  if (conn->connected()) {
    conn->setTcpNoDelay(true);
  }
}

void onMessage(const TcpConnectionSharedPtr& conn,
               Buffer* buf,
               base::TimeTicks) {
  std::string msg(buf->retrieveAllAsString());
  conn->send(msg);
}

int main(int argc, char* argv[]) {
  if (argc < 2) {
    fprintf(stderr, "Usage: server <port>\n");
    return 1;
  } else {
    EnsureNevInit();

    uint16_t port = static_cast<uint16_t>(atoi(argv[1]));
    IPEndPoint listen_addr(IPAddress::IPv4Localhost(), port);

    EventLoop loop;

    TcpServer server(&loop, listen_addr);
    server.setConnectionCallback(onConnection);
    server.setMessageCallback(onMessage);
    server.start();

    loop.loop();

    return 0;
  }
}
@hilarryxu hilarryxu added the Doc 教程文档 label Dec 2, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Doc 教程文档
Projects
None yet
Development

No branches or pull requests

1 participant