m_address.sin_family=AF_INET; m_address.sin_addr.S_un.S_addr=ip; m_address.sin_port=htons(port); int r=connect(m_socket,(sockaddr*)&m_address,sizeof(sockaddr)); if(r==SOCKET_ERROR) { m_lastError.Format("Fail to connect to the host. Reason[%d].",WSAGetLastError()); return FALSE; } return TRUE; }void CTelnetSocket::Close() { closesocket(m_socket); }int CTelnetSocket::Send(const char * pBuffer,int length,int timeout)//pending { // Does not support timeout sending at the moment int r=send(m_socket,pBuffer,length,0); if(r==SOCKET_ERROR) { m_lastError.Format("Error occured when sending data Reason[%d].",WSAGetLastError()); return 1; } return 0; }int CTelnetSocket::Receive(char * pBuffer,int length,int timeout) { if(waitForReadSignal(timeout)) return SOCKET_ERROR; int r=recv(m_socket,pBuffer,length,0); if(r==SOCKET_ERROR) { m_lastError.Format("Error occured when reveiving data Reason[%d].",WSAGetLastError()); return SOCKET_ERROR; } return r; }///////////////////////////////////////////////////////////////////////////// // // // // Return value: 0 there are some data to be read in the socket // 1 there is no data in the socket // 2 other circumstance such as error occured ///////////////////////////////////////////////////////////////////////////// int CTelnetSocket::waitForReadSignal(int timeout) { // Reset m_event WSAResetEvent(m_event); // Select the FD_READ and FD_CLOSE event if( WSAEventSelect(m_socket,m_event,(FD_READ|FD_CLOSE))==SOCKET_ERROR) { m_lastError.Format("Failed to run WSAEventSelect() Reason[%d].",WSAGetLastError()); return 2; } // Wait for the events int flag=0; int r=WaitForSingleObject(m_event,timeout);
switch(r) { case WAIT_OBJECT_0: flag=0; break; case WAIT_TIMEOUT: m_lastError.Format("Wait time out"); flag=1; break; case WAIT_FAILED: m_lastError.Format("Wait failed. Reason[%d].",WSAGetLastError()); flag=2; break; default: m_lastError.Format("Error occured when waiting for WSAEvent. Reason[%d].",WSAGetLastError()); flag=2; break; }
if(flag!=0) return flag;
// Find out which event has been invoked WSANETWORKEVENTS networkEvent; r=WSAEnumNetworkEvents(m_socket,m_event, &networkEvent); if(r==SOCKET_ERROR) { m_lastError.Format("Error occured when trying to get the detail of the event. Reason[%d].",WSAGetLastError()); return 2; } else { if(networkEvent.lNetworkEvents & FD_READ) { if(networkEvent.iErrorCode[FD_READ_BIT]==0) { return 0; } else { m_lastError.Format("Error occured when trying to get the detail of the event."); return 2; }
2 自己封装我有一个自己封装的
//
// Purpose:
//
// Required Classes:
//
// LastUpdatedTime:
//////////////////////////////////////////////////////////////////////#if !defined(AFX_TELNETSOCKET_H__377FC0ED_3B8A_41B6_8AA0_371515D05952__INCLUDED_)
#define AFX_TELNETSOCKET_H__377FC0ED_3B8A_41B6_8AA0_371515D05952__INCLUDED_#if _MSC_VER > 1000
#pragma once
#endifclass CTelnetSocket
{
public:
CTelnetSocket();
virtual ~CTelnetSocket();/////////////////////////////////////////////////////////////////////////////
// Member functions
/////////////////////////////////////////////////////////////////////////////
public:
BOOL Create();
BOOL Connect(const CString& host,int port);
void Close(); int Send(const char * pBuffer,int length,int timeout);
int Receive(char * pBuffer,int length,int timeout); const CString& getLastError(); //{{AFX_VIRTUAL(CTelnetSocket)
//}}AFX_VIRTUAL //{{AFX_MSG(CTelnetSocket)
//}}AFX_MSGprotected:
int waitForReadSignal(int timeout);/////////////////////////////////////////////////////////////////////////////
// Data members
/////////////////////////////////////////////////////////////////////////////
protected:
CString m_lastError; SOCKET m_socket;
SOCKADDR_IN m_address; WSAEVENT m_event;
};//{{AFX_INSERT_LOCATION}}
#endifCTelnet.cpp
// CTelnetSocket.cpp : Defines the class behaviors for the CTelnetSocket.
//
// LastUpdatedTime:
/////////////////////////////////////////////////////////////////////////////#include "stdafx.h"
#include "Telnetsocket.h"#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif/////////////////////////////////////////////////////////////////////////////
// Message mapping
/////////////////////////////////////////////////////////////////////////////
#if 0
BEGIN_MESSAGE_MAP(CTelnetSocket, CAsyncSocket)
//{{AFX_MSG_MAP(CTelnetSocket)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
#endif
/////////////////////////////////////////////////////////////////////////////
// Construction/Destruction
/////////////////////////////////////////////////////////////////////////////
CTelnetSocket::CTelnetSocket()
{
// Reset m_lastError
m_lastError=""; // Initialize m_event
m_event=WSACreateEvent();
if(m_event==WSA_INVALID_EVENT)
{
m_lastError.Format("Fail to initialize the m_event. Reason[%d].",WSAGetLastError());
}
WSAResetEvent(m_event); // WSAStartup
WSADATA wsaData;
WORD version=MAKEWORD(2,0);
if(WSAStartup(version,&wsaData)!=0)
{
m_lastError.Format("Fail to run WSAStartup().Reason[%d].",WSAGetLastError());
}
}CTelnetSocket::~CTelnetSocket()
{
if(m_socket!=NULL)
Close();
WSACleanup();
}/////////////////////////////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////////////////////////////
const CString& CTelnetSocket::getLastError()
{
return m_lastError;
}
/////////////////////////////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////////////////////////////
BOOL CTelnetSocket::Create()
{
// Initialize m_socket
if(m_socket!=NULL)
closesocket(m_socket);
m_socket=socket(AF_INET,SOCK_STREAM,0);
if(m_socket==INVALID_SOCKET)
{
m_lastError.Format("Fail to create the host. Reason[%d].",WSAGetLastError());
return FALSE;
} return TRUE;
}BOOL CTelnetSocket::Connect(const CString& host,int port)
{
unsigned long ip;
if( host[0]<= '9' && host[0]>='0' )
{
if((ip = inet_addr(host)) == INADDR_NONE)
{
m_lastError="Invalid IP address.";
return FALSE;
}
}
else
{
hostent* ent = gethostbyname(host);
if(!ent)
{
m_lastError="Invalid host name.";
return FALSE;
}
memcpy((char FAR *)&ip, ent->h_addr, ent->h_length);
}
m_address.sin_family=AF_INET;
m_address.sin_addr.S_un.S_addr=ip;
m_address.sin_port=htons(port);
int r=connect(m_socket,(sockaddr*)&m_address,sizeof(sockaddr)); if(r==SOCKET_ERROR)
{
m_lastError.Format("Fail to connect to the host. Reason[%d].",WSAGetLastError());
return FALSE;
} return TRUE;
}void CTelnetSocket::Close()
{
closesocket(m_socket);
}int CTelnetSocket::Send(const char * pBuffer,int length,int timeout)//pending
{
// Does not support timeout sending at the moment int r=send(m_socket,pBuffer,length,0);
if(r==SOCKET_ERROR)
{
m_lastError.Format("Error occured when sending data Reason[%d].",WSAGetLastError());
return 1;
} return 0;
}int CTelnetSocket::Receive(char * pBuffer,int length,int timeout)
{
if(waitForReadSignal(timeout))
return SOCKET_ERROR; int r=recv(m_socket,pBuffer,length,0);
if(r==SOCKET_ERROR)
{
m_lastError.Format("Error occured when reveiving data Reason[%d].",WSAGetLastError());
return SOCKET_ERROR;
} return r;
}/////////////////////////////////////////////////////////////////////////////
//
//
//
// Return value: 0 there are some data to be read in the socket
// 1 there is no data in the socket
// 2 other circumstance such as error occured
/////////////////////////////////////////////////////////////////////////////
int CTelnetSocket::waitForReadSignal(int timeout)
{
// Reset m_event
WSAResetEvent(m_event); // Select the FD_READ and FD_CLOSE event
if( WSAEventSelect(m_socket,m_event,(FD_READ|FD_CLOSE))==SOCKET_ERROR)
{
m_lastError.Format("Failed to run WSAEventSelect() Reason[%d].",WSAGetLastError());
return 2;
} // Wait for the events
int flag=0;
int r=WaitForSingleObject(m_event,timeout);
switch(r)
{
case WAIT_OBJECT_0:
flag=0;
break;
case WAIT_TIMEOUT:
m_lastError.Format("Wait time out");
flag=1;
break;
case WAIT_FAILED:
m_lastError.Format("Wait failed. Reason[%d].",WSAGetLastError());
flag=2;
break;
default:
m_lastError.Format("Error occured when waiting for WSAEvent. Reason[%d].",WSAGetLastError());
flag=2;
break;
}
if(flag!=0)
return flag;
// Find out which event has been invoked
WSANETWORKEVENTS networkEvent;
r=WSAEnumNetworkEvents(m_socket,m_event, &networkEvent);
if(r==SOCKET_ERROR)
{
m_lastError.Format("Error occured when trying to get the detail of the event. Reason[%d].",WSAGetLastError());
return 2;
}
else
{
if(networkEvent.lNetworkEvents & FD_READ)
{
if(networkEvent.iErrorCode[FD_READ_BIT]==0)
{
return 0;
}
else
{
m_lastError.Format("Error occured when trying to get the detail of the event.");
return 2;
}
}
if(networkEvent.lNetworkEvents & FD_CLOSE)
{
m_lastError.Format("Connection closed.");
return 2;
}
else
{
m_lastError.Format("Unknown events.");
return 2;
}
}
}