clientsocket.cpp

来自「a self encapsulated socket lib」· C++ 代码 · 共 70 行

CPP
70
字号
#include "ClientSocket.h"
#include <iostream>

using namespace std;

ClientSocket::ClientSocket(void)
{
	InitSocket();
}

ClientSocket::~ClientSocket(void)
{
	closesocket(m_ClientSocket);
	WSACleanup();
}

//connect to server
int ClientSocket::Connect()
{	
	int Ret = connect(m_ClientSocket,(struct sockaddr*)&m_serverAddr, sizeof(m_serverAddr));
    /*if ( Ret == SOCKET_ERROR )
    {
		throw "Connect Error!";	
    }	*/
	return Ret;
}

//accomplish the connection request
int ClientSocket::Connect(const char* username, const char* password)
{
	if (Connect() != ERR) {
		char buff[MAX_PATH];
		strcpy(buff, username);
		strcat(buff, "\1");
		strcat(buff, password);
		if (ERR == SendBuff(m_ClientSocket, buff)) return ERR;
		
		RecvBuff(m_ClientSocket, buff);
		if (buff[0] == '1') return 0; //1 stand for connected successfully
		else return 1;				  //0 indicates wrong username or password or both
	}
	else return ERR;
}

int ClientSocket::Receive() //start up the listenning thread
{
	return BaseSocket::Receive(m_ClientSocket);
}

int ClientSocket::Send(std::string data) // send data via the connection
{
	return SendBuff(m_ClientSocket, data.c_str());	
}

int ClientSocket::InitSocket()
{
	if (Startup() == ERR) return ERR;
	//Create Socket
	m_ClientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if ( m_ClientSocket == INVALID_SOCKET )
		return ERR;

	m_serverAddr.sin_family = AF_INET;
    m_serverAddr.sin_addr.s_addr = inet_addr(IP_ADDRESS);
	m_serverAddr.sin_port = htons(PORT);
	memset(m_serverAddr.sin_zero, 0x00, 8);

	return 0;
}

⌨️ 快捷键说明

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