client_connector.hpp

来自「本程序是主要是扫雷」· HPP 代码 · 共 139 行

HPP
139
字号
/*     Copyright(c) Ben Bear 2003-2004  */

//  This program is free software; you can redistribute it and/or
//  modify it under the terms of the GNU General Public License as
//  published by the Free Software Foundation; either version 2 of the
//  License, or (at your option) any later version.
//  
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  General Public License for more details.
//  
//  You should have received a copy of the GNU General Public License
//  along with this program; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
//  02111-1307, USA.

#ifndef __client_connector_hpp
#define __client_connector_hpp

#include <cassert>

#include "connector.hpp"
#include "info.hpp"

class client_con: public connector
{
protected:
  int client_sock;

  bool connect (unsigned int ip);
  void close ();

  int recv_int ();
  void send_int (int n);
  bool recv_bool ();
  void send_bool (bool b);
  void recv_name (char* name);
  void send_name (const char* name);

public:
  client_con ();
  ~client_con ();
};

client_con::client_con ()
{
  client_sock = -1;
}

client_con::~client_con ()
{
  close ();
}

bool
client_con::connect (unsigned int ip)
{
  client_sock = socket (AF_INET, SOCK_STREAM, 0);
  if (client_sock == INVALID_SOCKET)
    {
      client_sock = -1;
      throw "Can't create the client socket!";
    }

  struct sockaddr_in addr;
  addr.sin_family = AF_INET;
  addr.sin_addr.s_addr = htonl(ip);
  addr.sin_port = htons(SERVER_PORT);
  if (::connect (client_sock, (struct sockaddr*) &addr, sizeof (addr))
      == SOCKET_ERROR)
    {
      client_sock = -1;
      throw "Can't connect to the server!";
    }
  return true;
}

void
client_con::close ()
{
  if (client_sock != -1)
    ::closesocket (client_sock);
}

int
client_con::recv_int ()
{
  assert (client_sock != -1);

  int n;
  connector::recv_int (client_sock, n);
  return n;
}

void
client_con::send_int (int n)
{
  assert (client_sock != -1);

  connector::send_int (client_sock, n);
}

bool
client_con::recv_bool ()
{
  assert (client_sock != -1);

  bool b;
  connector::recv_bool (client_sock, b);
  return b;
}

void
client_con::send_bool (bool b)
{
  assert (client_sock != -1);

  connector::send_bool (client_sock, b);
}

void
client_con::recv_name (char* name)
{
  assert (client_sock != -1);

  connector::recv_name (client_sock, name);
}

void
client_con::send_name (const char* name)
{
  assert (client_sock != -1);

  connector::send_name (client_sock, name);
}

#endif

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?