当前位置:   article > 正文

windows API(TCP/IP)通讯编程_window api tcp通讯

window api tcp通讯

server端程序:


  1. #include <winsock2.h>#include <stdio.h>#include <stdlib.h>#include <windows.h>#include <process.h>#pragma comment(lib,"Ws2_32")#define DEFAULT_PORT 5150#define DEFAULT_BUFFER 4096int iPort = DEFAULT_PORT;BOOL bInterface = FALSE,bRecvOnly = FALSE;char szAddress[128];void usage(){ printf("usage:server[-p:x] [-i:IP] [-o]/n/n"); printf("       -p:x   Port number to listen on/n"); printf("       -i:str Interface to listen on/n"); printf("       -o     Don't echo the data back/n/n"); ExitProcess(1);}void ValidateArgs(int argc,char **argv){ int i; for(i=1;i<argc;i++) {  if((argv[i][0== '-')||(argv[i][0== '/'))  {   switch(tolower(argv[i][1]))   {   case 'p':    iPort = atoi(&argv[i][3]);    break;   case 'i':    bInterface = TRUE;    if(strlen(argv[i])>3)     strcpy(szAddress,&argv[i][3]);    break;   case 'o':    bRecvOnly = TRUE;    break;   default:    usage();    break;   }  } }}DWORD WINAPI ClientThread(LPVOID lpParam){ SOCKET sock = (SOCKET) lpParam; char   szBuff[DEFAULT_BUFFER]; int ret,nLeft,idx; while(1) {  ret = recv(sock,szBuff,DEFAULT_BUFFER,0);  if(ret == 0)   break;  else if(ret == SOCKET_ERROR)  {   printf("recv() failed:%d/n",WSAGetLastError());   break;  }  szBuff[ret]='/0';  printf("recv:'%s'/n",szBuff);  if(!bRecvOnly)  {   nLeft = ret;   idx = 0;   while(nLeft>0)   {    ret = send(sock,&szBuff[idx],nLeft,0);    if(ret == 0)     break;    else if (ret == SOCKET_ERROR)    {     printf("send() failed:%d/n",WSAGetLastError());     break;    }    nLeft -=ret;    idx+=ret;   }  } } return 0;}int main(int argc,char **argv){ WSADATA wsd; SOCKET sListen,sClient; int iAddrSize; HANDLE hThread; DWORD dwThreadId; struct sockaddr_in local,client; ValidateArgs(argc,argv); if(WSAStartup(MAKEWORD(2,2),&wsd) != 0) {  printf("failed to load winsock!/n");  return 1; } sListen = socket(AF_INET, SOCK_STREAM,IPPROTO_IP); if(sListen == SOCKET_ERROR) {  printf("socket() failed:%d/n",WSAGetLastError());  return 1; } else  printf("socket() successful!/n"); if(bInterface) {  local.sin_addr.s_addr = inet_addr(szAddress);  if(local.sin_addr.s_addr==INADDR_NONE)   usage(); } else  local.sin_addr.s_addr = htonl(INADDR_ANY); local.sin_family= AF_INET; local.sin_port = htons(iPort); if(bind(sListen,(struct sockaddr *&local,sizeof(local)) == SOCKET_ERROR) {  printf("bind() failed:%d/n",WSAGetLastError());  return 1; } else  printf("bind() successful!/n"); int listenState = listen(sListen, 8); printf("%d/n",listenState); while(1) {  iAddrSize = sizeof(client);  sClient = accept(sListen,(struct sockaddr *&client,&iAddrSize);  if(sClient ==INVALID_SOCKET)  {   printf("accept() failed:%d/n",WSAGetLastError());   break;  }  printf("Accept client:%s:%d/n",inet_ntoa(client.sin_addr),ntohs(client.sin_port));  hThread = ::CreateThread(NULL,0,ClientThread,(LPVOID)sClient,0,&dwThreadId);  if(hThread == NULL)  {   printf("creatThread() failed:%d/n",GetLastError());   break;  }  CloseHandle(hThread); } closesocket(sListen); WSACleanup(); return 0;}

client端程序:

  1. #include <winsock2.h>#include <stdio.h>#include <stdlib.h>#pragma comment(lib,"Ws2_32")#define DEFAULT_COUNT 20#define DEFAULT_PORT 5150#define DEFAULT_BUFFER 2048#define DEFAULT_MESSAGE "This is a test of the emergency broadcasting system" char szServer[128],szMessage[1024];int iPort = DEFAULT_PORT;DWORD  dwCount = DEFAULT_COUNT;BOOL bSendOnly = FALSE;void usage(){ printf("usage:client  [-p:x] [-i:IP] [-o]/n/n"); printf("       -p:x   Remote port to send to/n"); printf("       -s:IP  server's IP address or host name/n"); printf("       -n:x   number of times to send message/n"); printf("       -o     send message only; don't receive/n"); ExitProcess(1);}void ValidateArgs(int argc,char **argv){ int i; for(i=1;i<argc;i++) {  if((argv[i][0== '-')||(argv[i][0== '/'))  {   switch(tolower(argv[i][1]))   {   case 'p':    if (strlen(argv[i])>3)     iPort = atoi(&argv[i][3]);    break;   case 's':    if(strlen(argv[i])>3)     strcpy(szServer,&argv[i][3]);    break;   case 'n':    if(strlen(argv[i])>3)     dwCount = atol(&argv[1][3]);    break;   case 'o':    bSendOnly = TRUE;    break;   default:    usage();    break;   }  } }}int main(int argc, char **argv){ WSADATA wsd; SOCKET sClient; char szBuffer[DEFAULT_BUFFER]; int ret,i; struct sockaddr_in server; struct hostent *host = NULL; ValidateArgs(argc,argv); if(WSAStartup(MAKEWORD(2,2),&wsd)!=0) {  printf("failed to load winsock library!/n");  return 1; } strcpy(szMessage,DEFAULT_MESSAGE); sClient= socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if(sClient == INVALID_SOCKET) {  printf("socket() fialed: %d/n", WSAGetLastError());  return 1; } server.sin_family = AF_INET; server.sin_port = htons(iPort); server.sin_addr.s_addr = inet_addr("192.168.0.105"); if(server.sin_addr.s_addr == INADDR_NONE) {  host = gethostbyname(szServer);  if( host == NULL)  {   printf("Unable to resolve server:%s/n",szServer);   return 1;  }  CopyMemory(&server.sin_addr,host->h_addr_list[0],host->h_length ); } int m = connect(sClient,(struct sockaddr *)&server,sizeof(server)); if(m==SOCKET_ERROR) {  int errorCode = WSAGetLastError();  printf("connect() fialed:%d/n",errorCode);  return 1; } for(i =0;i < dwCount; i++) {  ret = send(sClient,szMessage,strlen(szMessage),0);  if(ret ==0)   break;  else if (ret==SOCKET_ERROR)  {   printf("send() fialed:%d/n",WSAGetLastError());   break;  }   printf("send %d bytes/n",ret);   if(!bSendOnly)   {    ret = recv(sClient,szBuffer,DEFAULT_BUFFER,0);    if(ret ==0)     break;    else if (ret == SOCKET_ERROR)    {     printf("recv() fialed:%d/n",WSAGetLastError());     break;    }    szBuffer[ret] = '/0';    printf("recv[%d bytes]:'%S'=n",ret,szBuffer);   }  }  closesocket(sClient);  WSACleanup();  return 0 ;  } 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/147014
推荐阅读
相关标签
  

闽ICP备14008679号