C++ 简单SOCKET 通信

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用
    #include "stdafx.h"  
    #include <Winsock2.h>  
    #include <stdio.h>  
    #include <iostream>  
    #include "SocketService.h"  
    #pragma comment(lib, "WS2_32")  
    using std::string;  
    namespace SocketService  
    {  
     //监听端:   
    void WINAPI StartToListen(void (*p)())  
    {  
    WORD wVersionRequested;  
    WSADATA wsaData;  
    int err;  
    wVersionRequested = MAKEWORD(1,1);  
    err = WSAStartup(wVersionRequested, &wsaData);  
    if ( err != 0 )  
     {  
      return;  
     }  
     if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1 )   
     {  
      WSACleanup();  
      return;  
     }  
     SOCKET sockSrv=socket(AF_INET,SOCK_STREAM,0);  
     SOCKADDR_IN addrSrv;  
     addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY);  
     addrSrv.sin_family=AF_INET;  
     addrSrv.sin_port=htons(8000);  
       
     bind(sockSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));  
     listen(sockSrv,5);  
     SOCKADDR_IN addrClient;  
     int len=sizeof(SOCKADDR);  
     while(1)  
     {  
      SOCKET sockConn=accept(sockSrv,(SOCKADDR*)&addrClient,&len);  
      p();  
      char sendBuf[50];  
      send(sockConn,sendBuf,strlen(sendBuf)+1,0);  
      char recvBuf[50];  
      recv(sockConn,recvBuf,50,0);  
      p();  
      closesocket(sockConn);  
     }  
    }  
    //发送端  
    void WINAPI Send(char* ipAddress,char* message)  
    {  
    WORD wVersionRequested;  
     WSADATA wsaData;  
     int err;  
       
     wVersionRequested = MAKEWORD(1,1);  
       
     err = WSAStartup( wVersionRequested, &wsaData );  
     if ( err != 0 ) {  
      return;  
     }  
       
     if ( LOBYTE( wsaData.wVersion ) != 1 ||  
             HIBYTE( wsaData.wVersion ) != 1 ) {  
       WSACleanup( );  
      return;  
     }  
     SOCKET sockClient=socket(AF_INET,SOCK_STREAM,0);  
       
     SOCKADDR_IN addrSrv;  
     addrSrv.sin_addr.S_un.S_addr=inet_addr(ipAddress);  
     addrSrv.sin_family=AF_INET;  
     addrSrv.sin_port=htons(8000);  
     connect(sockClient,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));  
     send(sockClient,message,strlen(message)+1,0);  
       
     closesocket(sockClient);  
     WSACleanup();  
    }  
    }  

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:Ajax之DWR学习

下一篇:查询最近10天开户的银行卡的信息,利用datediff()函数,计算开户日期和当前日期相差的天数