关于C++(MFC)Socket通讯

关于C++(MFC)Socket通讯

1、SocketUtil.h

// Socket函数头文件
// add by jzh 2011-04-06

#ifndef SocketUtil
#define SocketUtil
#include <windows.h>

// 创建连接,被用于CreateServerSocket、ConnectServer的初始化。
BOOL CreateSocket(DWORD dwReadTimeOut, DWORD dwSendTimeOut, DWORD &dwSocketHandle);

// 关闭连接
void CloseSocket(DWORD &dwSocketHandle);

// 创建服务端监听
BOOL CreateServerSocket(DWORD dwPortNumber, DWORD dwReadTimeOut, DWORD dwSendTimeOut, DWORD &dwSocketHandle);

// 接收客户端
BOOL AcceptClient(DWORD dwServerSocket, DWORD &dwClientSocket, LPSTR pszClientIP, DWORD dwSize);

// 连接服务端
BOOL ConnectServer(LPCSTR pszServerIP, DWORD dwPortNumber, DWORD dwReadTimeOut, DWORD dwSendTimeOut, DWORD &dwClientSocket);

// 接收数据
BOOL SocketRead(DWORD dwSocket, BYTE *pBuffer, DWORD &dwSize);
    
// 发送数据
BOOL SocketWrite(DWORD dwSocket, const BYTE *pBuffer, DWORD dwSize);

#endif

2、SocketUtil.cpp

// Socket函数实现文件
// add by jzh 2011-04-06
#include "stdafx.h"

#include "SocketUtil.h"
#include <Winsock2.h>

#pragma comment(lib, "Ws2_32.lib")

// 创建连接
BOOL CreateSocket(DWORD dwReadTimeOut, DWORD dwSendTimeOut, DWORD &dwSocketHandle)
{
    BOOL bRetval = TRUE;
    static BOOL WSA_Initialized = FALSE;
    if (FALSE == WSA_Initialized)
    {
        WSADATA wsaData;
        WORD wVersionRequested = MAKEWORD( 2, 2 );
    // 初始化
        if(0 != WSAStartup(wVersionRequested, &wsaData))
    {
            bRetval = FALSE;
    }
        else
    {
            WSA_Initialized = TRUE;
    }
    }

    int iSocket = -1;
  
  // 
    if((iSocket=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP))==INVALID_SOCKET)
  {
        bRetval = FALSE;
    }
    else
    {
        dwSocketHandle = iSocket;
    // 接收时限
        setsockopt(iSocket, SOL_SOCKET, SO_RCVTIMEO, (char*)(&dwReadTimeOut), sizeof(dwReadTimeOut));
    // 发送时限
    	setsockopt(iSocket, SOL_SOCKET, SO_SNDTIMEO, (char*)&dwSendTimeOut, sizeof(dwSendTimeOut));
    }
    return bRetval;
}

// 关闭连接
void CloseSocket(DWORD &dwSocketHandle)
{
    if (INVALID_SOCKET != dwSocketHandle)
  {
        closesocket(dwSocketHandle);
  }
}

// 创建服务端监听
BOOL CreateServerSocket(DWORD dwPortNumber, DWORD dwReadTimeOut, DWORD dwSendTimeOut,DWORD &dwSocketHandle)
{
    BOOL bRetval = TRUE;
    dwSocketHandle = 0;
    bRetval = CreateSocket(dwReadTimeOut, dwSendTimeOut, dwSocketHandle);
    if (TRUE == bRetval)
    {
        sockaddr_in server_addr;
        memset(&server_addr, 0, sizeof(struct sockaddr_in));
      server_addr.sin_family = AF_INET;
      server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
      server_addr.sin_port = htons(dwPortNumber);
      if(bind(dwSocketHandle, (struct sockaddr *)(&server_addr), sizeof(struct sockaddr))==-1)
      {
            bRetval = FALSE;
      }
    }
   
    if (TRUE == bRetval) //Set no blocking
    {
        unsigned long ulType = 1;
        if (0 != ioctlsocket(dwSocketHandle, FIONBIO, &ulType))
    {
            bRetval = FALSE;
    }
    }


    if (TRUE == bRetval)
    {
        if(listen(dwSocketHandle,2)==-1)
      {
            bRetval = FALSE;
        }
    }

    if (FALSE == bRetval)
    {
        if (0 != dwSocketHandle)
        {
           CloseSocket(dwSocketHandle);
        }
    }
    return bRetval;
}

// 接收客户端
BOOL AcceptClient(DWORD dwServerSocket, DWORD &dwClientSocket, LPSTR pszClientIP, DWORD dwSize)
{
    BOOL bRetval = TRUE;

  struct sockaddr_in client_addr;
  int iSocket = INVALID_SOCKET;
  int iSInSize; //sockaddr_in
  iSInSize = sizeof(struct sockaddr_in);
  if((iSocket = accept(dwServerSocket, (struct sockaddr *)(&client_addr), (int FAR*)(&iSInSize)))<=0)
  {
    bRetval = FALSE;
  }
  else
  {
    dwClientSocket = iSocket;
    char *pszIP = inet_ntoa(client_addr.sin_addr);
    int iLen = strlen(pszIP);
    if (iLen > dwSize -1)
    {
      iLen = dwSize -1;
    }
    memset(pszClientIP, 0, dwSize);
    strncpy(pszClientIP, pszIP, iLen);
    }

    return bRetval;
}

// 连接服务端
BOOL ConnectServer(LPCSTR pszServerIP, DWORD dwPortNumber, DWORD dwReadTimeOut, DWORD dwSendTimeOut, DWORD &dwClientSocket)
{
  BOOL bRetval = TRUE;
  bRetval = CreateSocket(dwReadTimeOut, dwSendTimeOut, dwClientSocket);
  if (TRUE == bRetval)
  {
    SOCKET sock = dwClientSocket;  
    struct sockaddr_in tagAddr;
    memset(&tagAddr, 0, sizeof(tagAddr));
    tagAddr.sin_addr.s_addr = inet_addr(pszServerIP);
    tagAddr.sin_family = AF_INET;
    tagAddr.sin_port = htons(dwPortNumber);
    if(connect(sock, (struct sockaddr *)&tagAddr, sizeof(tagAddr))==0)
    {
      //
    }
    else
    {
      CloseSocket(dwClientSocket);
      bRetval = FALSE;
    }
  }
  
  return bRetval;
}

// 接收数据
BOOL SocketRead(DWORD dwSocket, BYTE *pBuffer, DWORD &dwSize)
{
    BOOL bRetval = TRUE;
    struct timeval tv;
    tv.tv_sec = 0;
  tv.tv_usec = 0;
  fd_set r;

  FD_ZERO(&r);
  FD_SET(dwSocket, &r);
    DWORD dwBuffSize = dwSize;
    dwSize = 0;
    int iRet = select(dwSocket + 1, &r, NULL, NULL, &tv);
    if (iRet > 0)
    {
    iRet = recv(dwSocket, (char *)pBuffer, dwBuffSize, 0);
        if(iRet > 0 )
        {
            dwSize = iRet;
    	}
        else
    {
            bRetval = FALSE;
    }
    }
    else if (iRet < 0) //Socket broken
  {
        bRetval = FALSE;
  }

    return bRetval;
}

// 发送数据
BOOL SocketWrite(DWORD dwSocket, const BYTE *pBuffer, DWORD dwSize)
{
    BOOL bRetval = TRUE;
    struct timeval tv;
    tv.tv_sec = 0;
  tv.tv_usec = 0;
  fd_set r;

  FD_ZERO(&r);
  FD_SET(dwSocket, &r);
    int iRet = select(dwSocket + 1, NULL, &r, NULL, &tv);
    if (iRet > 0)
    {
        if(send(dwSocket, (char*)pBuffer, dwSize, 0) ==-1 )
      {
        bRetval = FALSE;
      }
    }
    else
  {
        bRetval = FALSE;
  }
    return bRetval;
}

 

发表回复

您的电子邮箱地址不会被公开。