C++ 简单SOCKET 通信
2018-07-20 来源:open-open
#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
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
最新资讯
热门推荐