c++ 简单SOCKET 通信

 

#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();
}
}


你可能感兴趣的:(C++,socket,Stream,include,winapi)