• Socket (二) 简单的代码实现


    SocktServer.cpp

    #include "stdafx.h"
    #pragma comment(lib,"ws2_32.lib")
    #include <Winsock2.h> 
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    	WORD wVersionRequested; 
     WSADATA wsaData; 
     int err; 
       
     wVersionRequested = MAKEWORD( 1, 1 ); 
       
     err = WSAStartup( wVersionRequested, &wsaData ); 
     if ( err != 0 ) { 
      return 0; 
     } 
       
     if ( LOBYTE( wsaData.wVersion ) != 1 || 
            HIBYTE( wsaData.wVersion ) != 1 ) { 
      WSACleanup( ); 
      return 0; 
     } 
     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(8080); 
       
     bind(sockSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR)); 
      
     listen(sockSrv,5); 
      
     SOCKADDR_IN addrClient; 
     int len=sizeof(SOCKADDR); 
     while(1) 
     { 
      printf("in while
    ");
      SOCKET sockConn=accept(sockSrv,(SOCKADDR*)&addrClient,&len); //服务端会在此一直等到客户端连接,只有客户端连接成功后,才会执行后续语句
      printf("have a client connecting
    ");
      char sendBuf[50]; 
      sprintf(sendBuf,"Welcome %s ",inet_ntoa(addrClient.sin_addr)); 
      send(sockConn,sendBuf,strlen(sendBuf)+1,0); 
      char recvBuf[50]; 
    
      for (int j = 0; j < 50; j++)
      {
    	  recvBuf[j] = NULL;
      }
      recv(sockConn,recvBuf,50,0); 
    
      printf("%s
    ",recvBuf); 
      closesocket(sockConn); 
     } 
      
    	return 0;
    }
    

     SocktClient.cpp

    #include "stdafx.h"
    #pragma comment(lib,"ws2_32.lib")
    #include <Winsock2.h> 
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    	WORD wVersionRequested;
     WSADATA wsaData;
     int err;
     
     wVersionRequested = MAKEWORD( 1, 1 );
     
     err = WSAStartup( wVersionRequested, &wsaData );
     if ( err != 0 ) {
      return 0;
     }
     
     if ( LOBYTE( wsaData.wVersion ) != 1 ||
            HIBYTE( wsaData.wVersion ) != 1 ) {
      WSACleanup( );
      return 0;
     }
     SOCKET sockClient=socket(AF_INET,SOCK_STREAM,0);
     
     SOCKADDR_IN addrSrv;
     addrSrv.sin_addr.S_un.S_addr=inet_addr("192.168.0.127");
     addrSrv.sin_family=AF_INET;
     addrSrv.sin_port=htons(8080);
     connect(sockClient,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
     send(sockClient,"00000",strlen("11111 ")+1,0);
     char recvBuf[50];
     recv(sockClient,recvBuf,50,0);
     printf("%s
    ",recvBuf);
     
     closesocket(sockClient);
     WSACleanup();
    	return 0;
    }
    
  • 相关阅读:
    Backbone Events 源码笔记
    IIS8集成模式下打开静态资源被aspx处理程序处理,StaticFileModule失效问题分析
    Orchard 与 ABP架构比较 (aspnetboilerplate)
    Orchard EventBus 事件总线及 IEventHandler作用
    Orchard 事件通知小坑
    推荐一个国内编程语言排名网站
    po_文件格式[转]
    关于poedit打开po文件乱码的问题
    JAVA和.NET工作流相关项目收集
    php里的二进制安全
  • 原文地址:https://www.cnblogs.com/blogwww/p/9508904.html
Copyright © 2020-2023  润新知