首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ Builder >

BCB中Socket编程,无法Create解决方案

2012-02-12 
BCB中Socket编程,无法Create//socket.cpp#include winsock2.h//Socket类声明如下:class CNtpSocket{publ

BCB中Socket编程,无法Create
//socket.cpp

#include <winsock2.h>

//Socket类声明如下:
class CNtpSocket
{
public:
  CNtpSocket();
  ~CNtpSocket();

  BOOL Create();
  BOOL Connect(const char* pszHostAddress, int nPort);
  BOOL Send(LPCSTR pszBuf, int nBuf);
  int Receive(LPSTR pszBuf, int nBuf);
  void Close();
  BOOL IsReadible(BOOL& bReadible, DWORD dwTimeout);

protected:
  BOOL Connect(const SOCKADDR* lpSockAddr, int nSockAddrLen);
  SOCKET m_hSocket;
};



//Create函数实现如下
BOOL CNtpSocket::Create()
{
  m_hSocket = socket(AF_INET, SOCK_DGRAM, 0);
  return (m_hSocket != INVALID_SOCKET);
}



//在项目另一处构造CNtpSocket类实例并Create一个socket
  CNtpSocket* pSocket = new CNtpSocket();
  if(!pSocket->Create())
  delete pSocket;

结果pSocket就被delete掉了
断点跟踪发现m_hSocket = socket(AF_INET, SOCK_DGRAM, 0);这一句话执行返回的m_hSocket为INVALID_SOCKET
这是怎么回事啊,望达人解惑

[解决办法]
WSAStartup初始化没有?
[解决办法]

C/C++ code
WSADATA wsaData;WORD sockVersion = MAKEWORD(2, 0);if (0 != WSAStartup(sockVersion, &wsaData)){   std::cout << "Failed to retrive socket version."     << std::endl;   return 0;}SOCKET sock_client;sock_client = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);if (INVALID_SOCKET == sock_client){   std::cout << "Invalid socket." << std::endl;   WSACleanup();   return 0;}sockaddr_in addr_sev;addr_sev.sin_family = AF_INET;addr_sev.sin_port = htons(PORT_SERVER);addr_sev.sin_addr.s_addr = inet_addr("127.0.0.1");if (SOCKET_ERROR == connect(sock_client, (sockaddr *)&addr_sev, sizeof(addr_sev))){   std::cout << "Failed to connect." << std::endl;   WSACleanup();   return 0;}char buf[512];int recv_size = 0;recv_size = recv(sock_client, buf, 512, 0);if (512 > recv_size){   buf[recv_size] = '\0';   std::cout << "receive data is :" << buf << std::endl;   memset(buf, 0, sizeof(buf));}else{   std::cout << "receive data is overflow" << std::endl;}closesocket(sock_client);WSACleanup();
[解决办法]
C/C++ code
WSADATA wsaData;WORD sockVersion = MAKEWORD(2, 0);if (0 != WSAStartup(sockVersion, &wsaData)){   std::cout << "Failed to retrive socket version."     << std::endl;   return 0;} 

热点排行