Windows TCP Client

#include   "stdafx.h"
#include   <WinSock2.h>
#include   <string>
#include   <iostream>

#pragma   comment (   lib ,   "WS2_32.lib"   )

const   static   int   _MAX_BUF_SIZE   = 256;

using   namespace   std ;

int   _tmain (   int   argc   ,   _TCHAR *   argv [])
{
        WSADATA   wsaData   ;
        if (   WSAStartup   (   MAKEWORD ( 2, 2 ), &   wsaData   ) != 0 )
     {
             cout << "WSAStartup   无法初始化   !"   << endl   ;
             return   -1;
     }

        SOCKET   sHost   ;
        sHost   =   socket   (   AF_INET ,   SOCK_STREAM ,   IPPROTO_TCP   );
        if (   INVALID_SOCKET   ==   sHost   )
     {
             cout << "socket failed !"   << endl ;
             WSACleanup ();
             return   -1;
     }

        SOCKADDR_IN   servAddr   ;
        servAddr . sin_family   =   AF_INET ;
        servAddr . sin_addr   . S_un .   S_addr   =   inet_addr   (   "192.168.1.44"   );
        servAddr . sin_port   =   htons (9990);
        int   sServerAddrLen   =   sizeof (   servAddr   );

     
        int   retVal   ;
        retVal   =   connect   (   sHost , (   LPSOCKADDR )& servAddr   ,   sizeof   ( servAddr ) );
        if (   SOCKET_ERROR   ==   retVal   )
     {
             cout << "connect failed !"   << endl ;
             closesocket (   sHost   );
             WSACleanup ();
             return   -1;
     }

        char   buf   [ _MAX_BUF_SIZE ];
        while (1)
     {
             cout << "Please input a string to send:"   << endl ;
             std :: string   str ;
             std :: getline   (   std ::   cin ,   str   );
             ZeroMemory (   buf   ,   _MAX_BUF_SIZE   );
             strcpy (   buf   ,   str .   c_str () );

             retVal   =   send   (   sHost ,   buf ,   strlen   ( buf ), 0 );
             if (   SOCKET_ERROR   ==   retVal   )
          {
                 cout << "send failed!"   << endl ;
                 closesocket ( sHost   );
                 WSACleanup ();
                 return   -1;
          }

             retVal   =   recv   (   sHost ,   buf ,   sizeof   ( buf ) + 1, 0 );
             cout << "Recv From Server: %s "   << buf <<   endl ;
             if (   strcmp   (   buf ,   "quit"   ) == 0 )
          {
                 cout << "quit!"   << endl ;
                 break ;
          }
     }
     
        closesocket (   sHost   );
        WSACleanup ();
        system ( "pause"   );
        return   0;
}
  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值