Socket 및 UDP 프로토콜을 기반으로 간단한 서버 구축 및 영어 기능 구현

5664 단어

서버


UDPsocket 패키지
#pragma once
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

typedef struct sockaddr sockaddr;
typedef struct sockaddr_in sockaddr_in;

class UdpSocket {
  public:
    UdpSocket() :
      fd_(-1) { }

    bool Socket() {
      fd_ = socket(AF_INET, SOCK_DGRAM, 0);// socket
      if (fd_ < 0) {
        perror("socket");
        return false;
      }
      return true;
    }

    bool Close() {
      close(fd_);
      return true;
    }

    // 
    bool Bind(const std::string &ip, uint16_t port) {
      sockaddr_in addr;
      addr.sin_family = AF_INET;
      addr.sin_addr.s_addr = inet_addr(ip.c_str());
      addr.sin_port = htons(port);
      int ret = bind(fd_, (sockaddr*)&addr, sizeof(addr));
      if (ret < 0) {
        perror("bind");
        return false;
      }
      return true;
    }

    bool RecvFrom(std::string* buf, std::string *ip = NULL, uint16_t *port = NULL) {
      char tmp[1024 * 10] = { 0 };
      sockaddr_in peer;
      socklen_t len = sizeof(peer);
      ssize_t read_size = recvfrom(fd_, tmp, sizeof(tmp) - 1, 0, (sockaddr*)&peer, &len);
      if (read_size < 0) {
        perror("recvform");
        return false;
      }

      // 
      buf->assign(tmp, read_size);
      if (ip != NULL) {
        *ip = inet_ntoa(peer.sin_addr);
      }
      if (port != NULL) {
        *port = ntohs(peer.sin_port);
        return true;
      }
    }

    bool SendTo(const std::string &buf, const std::string &ip, uint16_t port) {
      sockaddr_in addr;
      addr.sin_family = AF_INET;
      addr.sin_addr.s_addr = inet_addr(ip.c_str());
      addr.sin_port = htons(port);
      ssize_t write_size = sendto(fd_, buf.data(), buf.size(), 0, (sockaddr*)&addr, sizeof(addr));
      if (write_size < 0) {
        perror("sendto");
        return false;
      }
      return true;
    }

  private:
    int fd_;
};


UDP 공통 서버 구축
#pragma once
#include "udp_socket.hpp"

//C  
//typedef void (Handler*)(const std::string &req, std::dtring* resp);

#include 
typedef std::function Handler;

class UdpServer {
  public:
    UdpServer() {
      assert(sock_.Socket());
    }

    ~UdpServer() {
      sock_.Close();
    }

    bool Start(const std::string& ip, uint16_t port, Handler handler) {
      //1、 socket
      //2、 
      bool ret = sock_.Bind(ip, port);
      if (!ret) {
        return false;
      }
      //3、 
      while (1) {
        //4、 
        std::string req;
        std::string remote_ip;
        uint16_t remote_port = 0;
        bool ret = sock_.RecvFrom(&req, &remote_ip, &remote_port);
        if (!ret) {
          continue;
        }
        std::string resp;
        //5、 
        handler(req, &resp);
        //6、 
        sock_.SendTo(resp, remote_ip, remote_port);
        printf("[%s:%d] req: %s, resp: %s
", remote_ip.c_str(), remote_port, req.c_str(), resp.c_str()); } sock_.Close(); return true; } private: UdpSocket sock_; };

영역 서버 구현
// udp , 

#include "udp_server.hpp"
#include 
#include 

std::unordered_map<:string std::string=""> g_dict;

void Translate(const std::string& req, std::string *resp) {
  auto it = g_dict.find(req);
  if(it == g_dict.end()) {
    *resp = " !";
    return ;
  }
  *resp = it->second;
}

int main(int argc, char* argv[]){
  //printf("%d", argc);
  if(argc != 3) {
    printf ("Usage ./dict_server [ip] [port]
"); return 1; } //1、 g_dict.insert(std::make_pair("hello", " ")); g_dict.insert(std::make_pair("world", " ")); g_dict.insert(std::make_pair("JacksonYee", " ")); g_dict.insert(std::make_pair("cool", " ")); //2、 UdpServer server; server.Start(argv[1], atoi(argv[2]), Translate); return 0; }

클라이언트


UDP 공통 클라이언트 구현
#pragma once

#include 
#include "udp_socket.hpp"

class UdpClient {
public:
	UdpClient(const std::string& ip, uint16_t port) :
		ip_(ip),
		port_(port) {
		assert(sock_.Socket());
	}

	~UdpClient() {
		sock_.Close();
	}

	bool RecvFrom(std::string* buf) {
		return sock_.RecvFrom(buf);
	}

	bool SendTo(const std::string& buf) {
		return sock_.SendTo(buf, ip_, port_);
	}

private:
	UdpSocket sock_;

	// IP 
	std::string ip_;
	uint16_t port_;
};

영역 클라이언트 구현
#include "udp_client.hpp"
//#include 

int main(int argc, char* argv[]) {
  printf("%d
", argc); if (argc != 3) { printf("Usage ./dict_client [ip] [port]
"); return 1; } UdpClient client(argv[1], atoi(argv[2])); while (1) { std::string word; std::cout << "Please enter the word:"; std::cin >> word; if (!std::cin) { std::cout << "Bye~" << std::endl; break; } client.SendTo(word); std::string result; client.RecvFrom(&result); std::cout << word << "means: " << result << std::endl; } return 0; }

Socket 및 TCP 프로토콜을 기반으로 한 간단한 영어 기능 구현

좋은 웹페이지 즐겨찾기