简单Socket 封装类及应用

/****************************  **********************************/

 

LRESULT CVoltaProjDlg::OnServerMessage(WPARAM wParam, LPARAM lParam)

{

       SOCKET socket;

      

       int length,i;

       ID_CARD_INFO serverdata;

      

      

       switch(lParam)

       {

       case FD_ACCEPT:

              socket= accept(m_server.m_hSocket,NULL,NULL);

              m_server.m_connectionList.AddHead(socket);

              return 0;

             

       case FD_READ://接收到客户端信息

              length=m_server.m_connectionList.GetCount();

              for(i=0;i<length;i++)//循环寻找向服务器发送数据的客户端

              {

                     socket=m_server.m_connectionList.GetAt(m_server.m_connectionList.FindIndex(i));

                     if(socket==wParam)//找到客户端

                     {

                            recv(socket,(char*)&serverdata,DATASIZE,0);//服务器接收客户端发送的数据--s

                            if((cmd.num!=serverdata.num) || (cmd.on!= serverdata.on))

                            {

                                   cmd.num=serverdata.num;

                                   cmd.on= serverdata.on;

                            }

                           

                            return 0;

                     }

              }

              return 0;

             

       case FD_WRITE:

              return 0;

             

       case FD_CLOSE:

              AfxMessageBox("主机连接异常关闭!请重新启动主机程序,再启动客户机程序!");

              return 0;

             

       default:

             

              return 0;

       }

}

 

 

/**************************** Socket.h  ***********************************/

 

 

 

#include <math.h>

#include "atlbase.h"

#include <afxtempl.h>

 

#include "winsock.h"

#include  "afxsock.h"

#include <winnetwk.h>

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

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

 

 

typedef CList <SOCKET,SOCKET&> SOCKET_ARRAY;

 

 

typedef struct cardinfo

{

 

       int num;

       BOOL on;

       BOOL bShutFlag;

 

}ID_CARD_INFO,*ID_CARD_INFO_PTR;

 

 

 

#define DATASIZE  sizeof(ID_CARD_INFO)

 

#define SER_MESSAGE WM_USER + 100                 // 自定义消息

#define CLI_MESSAGE WM_USER + 101

 

 

//    在对话框上加上自定义消息响应

//     ON_MESSAGE(SER_MESSAGE,OnServerMessage)

//  

//    

class  CServer 

{

public:

public:

       CServer();

       virtual ~CServer();

private:

       void ServerInit();

public:

       BOOL InitAndListen(HWND hwnd,UINT port);

 

       static int GetLocalHostName(CString &sHostName);  //获得本地计算机名称

       static int GetIpAddress(const CString &sHostName, CString &sIpAddress);//获得本地IP

       static int GetIpAddress(const CString &sHostName, BYTE &f0,BYTE &f1,BYTE &f2,BYTE &f3);//获得本地IP

 

       BOOL CreateServer(HWND hwnd,UINT port);

 

 

public:

       SOCKET m_hSocket;

       sockaddr_in m_addr;

       UINT m_uPort;

    HWND m_hWnd;

 

       SOCKET_ARRAY m_connectionList;//客户机IP地址的第四个值及连接成功标志结构

 

 

};

 

 

//

//

class  CClient 

{

public:

       CClient();

       virtual ~CClient();

private:

       void ClientInit();

public:

       BOOL InitAndConnet(HWND hwnd,UINT port,CString strIP);

 

 

       static int GetLocalHostName(CString &sHostName);  //获得本地计算机名称

       static int GetIpAddress(const CString &sHostName, CString &sIpAddress);//获得本地IP

       static int GetIpAddress(const CString &sHostName, BYTE &f0,BYTE &f1,BYTE &f2,BYTE &f3);//获得本地IP

 

       BOOL Enumerate(LPNETRESOURCE lpNetRC_p,int depth);

       BOOL ConnectServer(HWND hwnd ,UINT port,CString strIP);

 

 

public:

       void SendData(ID_CARD_INFO &commdata);

       void RevData(ID_CARD_INFO commdata);

       void GetString(CString & str);

       void SendString(CString a);

      

       SOCKET m_hSocket;

       sockaddr_in m_addr;

       UINT m_uPort;

    HWND m_hWnd;

 

       CStringList     m_List;

       CStringList m_NeighborList;

 

       CString computer[50];

       int computer_count;

       int count;

};

 

 

/**************************** Socket.Cpp  **********************/

 

CServer::CServer()                            // 初始化版本库

{

       m_hSocket=NULL;

 

       WSADATA wsaData;

       WORD version = MAKEWORD(2, 0);

       int ret = WSAStartup(version, &wsaData);

       if(ret != 0)

       {

              TRACE("Initilize Error!/n");  //初始化失败网络

              AfxMessageBox("Failed in initial socket");

       }

 

 

 

       m_connectionList.RemoveAll();

       ASSERT(m_connectionList.GetCount()==0);

}

 

 

void CServer::ServerInit()   // 设置为非堵塞 套接字

// SER_MESSAGE  为自定义消息,指定接收到以下事件时发送// 自定义消息

{

       if(WSAAsyncSelect(m_hSocket, m_hWnd, SER_MESSAGE, FD_ACCEPT|FD_READ|FD_WRITE|FD_CLOSE)>0)

              AfxMessageBox("error select");

}

 

 

BOOL CServer::InitAndListen(HWND hwnd,UINT port)    

{

       m_uPort=port;

       m_hWnd=hwnd;

 

       if(m_hSocket != NULL)

    {

        //如果已经创建了套接字先关闭原来的

              closesocket(m_hSocket);

              m_hSocket = NULL;

       }

       if(m_hSocket == NULL)

       {

              //创建新的套接字,这里是创建的流类型的套接字

              m_hSocket = socket(AF_INET, SOCK_STREAM,0);

              ASSERT(m_hSocket != NULL);

              ServerInit();

       }

       m_addr.sin_family = AF_INET;

       m_addr.sin_addr.S_un.S_addr = INADDR_ANY;

       m_addr.sin_port = htons(m_uPort);

 

       int ret = 0;

       int error = 0;

       //绑定一个套接字到本机的地址

       ret = bind(m_hSocket, (LPSOCKADDR)&m_addr, sizeof(m_addr));

 

       if(ret == SOCKET_ERROR)

       {     //绑定错误

              AfxMessageBox("Binding Error");

              return FALSE;

       }

      

       //开始一个侦听过程,等待客户的连接

       ret = listen(m_hSocket, 10);    //这里的第二个参数表示最多支持的客户连接数

       if(ret == SOCKET_ERROR)

       {     //listen失败

              AfxMessageBox("Listen Error");

              return FALSE;

       }

 

       return TRUE;

}

 

 

BOOL CServer::CreateServer(HWND hwnd,UINT port)

{

       if(InitAndListen(hwnd,port)==FALSE)

       {

 

              return  FALSE;

       }

       else//把本机设为服务器

       {

              return  TRUE;

       }

}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值