Self-encapsulated socket class-socket_zmy

Source: Internet
Author: User
Tags htons

The function is simple and supports sending and receiving. Suitable for beginners.

Socket_zmy.h

#pragma once#define _AFXDLL#include "afxsock.h"#include "afxwin.h"class Socket_Zmy{public:Socket_Zmy(void);~Socket_Zmy(void);int SendData(CString IP, int Port, void * Data,int DataLen);int RecvData(int Port, char * Data, int DataLen);};

Socket_zmy.cpp

#include "Socket_Zmy.h"Socket_Zmy::Socket_Zmy(void){if (!AfxSocketInit()){AfxMessageBox("AfxSocketInit() Failed");}}Socket_Zmy::~Socket_Zmy(void){}int Socket_Zmy::SendData(CString IP, int Port, void * Data,int DataLen){SOCKET Socket = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);if(Socket == INVALID_SOCKET){AfxMessageBox("::socket() Failed");}sockaddr_in servAddr; servAddr.sin_family = AF_INET;servAddr.sin_port = htons(Port);servAddr.sin_addr.S_un.S_addr = inet_addr(IP);if(::connect(Socket,(sockaddr*)&servAddr, sizeof(servAddr)) == -1){AfxMessageBox("::connect() Failed");return 0;}int len = ::send(Socket,(const char *)Data,DataLen,0);::closesocket(Socket);return len;}int Socket_Zmy::RecvData(int Port, char * Data, int DataLen){SOCKET sListen = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);if(sListen == INVALID_SOCKET){AfxMessageBox("::socket() Failed");return 0;}sockaddr_in sin;sin.sin_family = AF_INET;sin.sin_port = htons(Port);sin.sin_addr.S_un.S_addr = INADDR_ANY;if(::bind(sListen,(LPSOCKADDR)&sin,sizeof(sin)) == SOCKET_ERROR){AfxMessageBox("::bind() Failed");return 0;}if(::listen(sListen, 2) == SOCKET_ERROR){AfxMessageBox("::listen() Failed");return 0;}sockaddr_in remoteAddr; int nAddrLen = sizeof(remoteAddr);SOCKET sClient = 0;while(sClient == 0){sClient = ::accept(sListen,(SOCKADDR*)&remoteAddr, &nAddrLen);if(sClient == INVALID_SOCKET){AfxMessageBox("::accept() Failed");}continue;}int nRecv = ::recv(sClient,Data,DataLen,0);if(nRecv > 0){Data[nRecv] = '\0';}::closesocket(sClient);::closesocket(sListen);return 0;}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.