TCP SOCKET封装类

聊天工具开发过程中,涉及到P2P技术。查阅相关资料,看网上推荐的比较好的列子hermes语音聊天系统。参考书《P2P网络技术原理与C++开发案例》。

书中简单介绍了TCP SOCKET操作的封装类,详细代码如下:

TCPSocket.h


// TCPSocket.h: interface for the CTCPSocket class.
//
//////////////////////////////////////////////////////////////////////

#if !defined(_TCPSOCKET_H_)
#define _TCPSOCKET_H_

#if _MSC_VER > 1000
#pragma once
#endif

#include "winsock2.h"

class CTCPSocket  
{
public:
	static int Initialize();
	static int CleanUp();
	
	CTCPSocket();
	CTCPSocket(SOCKET s);
	virtual ~CTCPSocket();

	int Create();
	int Bind(u_short port = DEFAULT_PORT);
	int Listen(int backlog = DEFAULT_BACKLOG);
	SOCKET Accept(sockaddr* addr = NULL, int* addrlen = NULL);

	int Connect(DWORD ip, u_short port = DEFAULT_PORT);
	int Send(const char *pBuf, int len);
	int Recv(char *pbuf, int len);

	int Close();
	
	SOCKET m_socket;
private:

	sockaddr_in m_local;
	sockaddr_in m_foreign;

	enum {DEFAULT_PORT = 56177, DEFAULT_BACKLOG = 1};
};

#endif //_TCPSOCKET_H_

TCPSocket.cpp

// TCPSocket.cpp: implementation of the CTCPSocket class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "TCPSocket.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
int CTCPSocket::Initialize()
{
	WSADATA wsd;
	
	return WSAStartup(MAKEWORD(2,2), &wsd);
}

int CTCPSocket::CleanUp()
{
	return WSACleanup();
}

CTCPSocket::CTCPSocket(SOCKET s)
{
	m_socket = s;
}

CTCPSocket::CTCPSocket()
{
	m_socket = INVALID_SOCKET;
}

CTCPSocket::~CTCPSocket()
{
}

int CTCPSocket::Create()
{
	m_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);

	return m_socket;
}

int CTCPSocket::Bind(u_short port /* = DEFAULT_PORT */)
{
	m_local.sin_addr.s_addr = htonl(INADDR_ANY);
	m_local.sin_family = AF_INET;
	m_local.sin_port = port;

	return bind(m_socket, (struct sockaddr*)&m_local, sizeof(m_local));
}

int CTCPSocket::Listen(int backlog)
{
	return listen(m_socket, backlog);
}

SOCKET CTCPSocket::Accept(sockaddr* addr /* = NULL */, int* addrlen /* = NULL */)
{
	return accept(m_socket, addr, addrlen);
}

int CTCPSocket::Connect(DWORD ip, u_short port /* = DEFAULT_PORT */)
{
	ip = htonl(ip);

	m_foreign.sin_addr.s_addr = ip;
	m_foreign.sin_family = AF_INET;
	m_foreign.sin_port = port;

	return connect(m_socket, (struct sockaddr*)&m_foreign, sizeof(m_foreign));
}

int CTCPSocket::Send(const char *pBuf, int len)
{
	return send(m_socket, pBuf, len, 0);
}

int CTCPSocket::Recv(char *pbuf, int len)
{
	return recv(m_socket, pbuf, len, 0);
}

int	 CTCPSocket::Close()
{
	int ret;

	ret = shutdown(m_socket,2);
	return closesocket(m_socket);
}


你可能感兴趣的:(通信技术)