📄 mysock.cpp
字号:
// MySock.cpp: implementation of the CMySock class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "NoSpam.h"
#include "MySock.h"
#include <assert.h>
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CMySock::CMySock()
{
S = INVALID_SOCKET;
}
CMySock::~CMySock()
{
Disconnect();
}
int CMySock::Connect(LPCSTR hostname, const int port)
{
Disconnect();
struct sockaddr_in A;
struct hostent* H;
if ((S = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) return 993;
if ((H = gethostbyname(hostname)) == NULL) return 921;
A.sin_family=AF_INET;
A.sin_port = htons(port);
A.sin_addr.s_addr=*((unsigned long*)H->h_addr);
if (connect(S,(struct sockaddr *) &A,sizeof(A)) == SOCKET_ERROR)
return (WSAGetLastError() == WSAETIMEDOUT ? 923 : 922);
return 0;
}
void CMySock::Disconnect()
{
if (S != INVALID_SOCKET)
{
//shutdown(S, SD_BOTH);
closesocket(S);
S = INVALID_SOCKET;
}
}
int CMySock::Send(const void* buf, const int len)
{
assert(buf != NULL);
int sent = 0;
while (sent < len)
{
int snt = send(S, &((const char*)buf)[sent], len-sent, 0);
if (snt == SOCKET_ERROR)
return (WSAGetLastError() == WSAETIMEDOUT ? 923 : 924);
sent += snt;
}
return 0;
}
int CMySock::Send(LPCSTR str)
{
return Send((const void*)str, lstrlen(str));
}
int CMySock::Receive(void* buf, int& len)
{
int bufLen = len;
len = 0;
if (bufLen > 0)
{
int rcv = recv(S, (char*)buf, bufLen, 0);
if (rcv == SOCKET_ERROR)
return (WSAGetLastError() == WSAETIMEDOUT ? 923 : 924);
len = rcv;
}
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -