|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
头文件>=================================================================================
#pragma once
#include<winsock2.h>
class Sockets
{
protected:
SOCKET m_hSocket;//核心成员变量
public:
BOOL Create(UINT nSocketProt = 0, int nSocketType = SOCK_STREAM,
LPCTSTR lpszSocketAddress = NULL);//端口,tcp /udp 数据流或者数据包 以及socket地址
int SendTo(const void*lpBuf, int lpBuflen, UINT rSockPort, char *rSocketAddress = NULL, int nFlags = 0);//缓冲区 长度 地址
int ReceiveFrom(void*lpBuf, int lpBuflen, char *rSocketAddRess, UINT&rSockaPort, int nFlags = 0);
int Receive(void*lpBuf, int lpBuflen,int nFlage = 0)
{
return recv(m_hSocket, (LPTSTR)lpBuf, lpBuflen, nFlage);
}
void Close()
{
closesocket(m_hSocket);
m_hSocket = INVALID_SOCKET;
}
Sockets();
virtual ~Sockets();
};
源文件>=================================================================================
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#include "Sockets.h"
#pragma comment(lib,"ws2_32.lib")
BOOL Sockets::Create(UINT nSocketProt, int nSocketType, LPCTSTR lpszSocketAddress)
{
m_hSocket = socket(AF_INET, nSocketType, 0);
if (m_hSocket == INVALID_SOCKET)
return FALSE;
sockaddr_in sa = {AF_INET, htons(nSocketProt)};
if(lpszSocketAddress)
sa.sin_addr.s_addr = inet_addr(lpszSocketAddress);
return !bind(m_hSocket, (sockaddr*)&sa, sizeof(sa));
}
int Sockets::SendTo(const void * lpBuf, int lpBuflen, UINT rSockPort, char * rSocketAddress, int nFlags)
{
sockaddr_in sa{ AF_INET,htons(rSockPort) };
sa.sin_addr.s_addr = inet_addr(rSocketAddress);
sendto(m_hSocket, (const char*)lpBuf, lpBuflen, 0, (sockaddr*)&sa, sizeof(sa));
return 0;
}
int Sockets::ReceiveFrom(void * lpBuf, int lpBuflen, char * rSocketAddRess, UINT & rSockaPort, int nFlags)
{
sockaddr_in sa{ AF_INET};
int nLen = sizeof(sa);
int n=recvfrom(m_hSocket, (char*)lpBuf,lpBuflen,0,(sockaddr*)&sa,&nLen);
if (n >= 0)
{
rSockaPort = htons(sa.sin_port);
strcpy(rSocketAddRess, inet_ntoa(sa.sin_addr));
}
return n;
}
Sockets::Sockets()
{
WSADATA wd;
WSAStartup(0x0202, &wd);
m_hSocket = INVALID_SOCKET;
}
Sockets::~Sockets()
{
Close();
}
|
评分
-
查看全部评分
|