win32 socket编程帮助

本文介绍使用Winsock进行异步客户端编程的基本步骤。包括创建套接字、填充SOCKADDR_IN结构体、连接服务器、发送接收数据及关闭套接字等过程。

http://msdn.microsoft.com/en-us/library/ms741394(v=vs.85)

client:

Socket programming in MFC is usually a bit messy. It's always clean and convenient to write the socket programs using Win32.

  A big advantage writing these programs in Win32 is, we can follow the same model as in any Unix C++ socket program. Also, with each and every new version of Winsock, we don't know how many bugs are going to get added to the development frameworks.

Anyway, now let's get down to business. This article does not try to cover all the minute details of winsock client programming, but for the basics. The relevant steps for creating a synchronous client socket are:

 

 

  1. Create a socket and get the handle
  2. Populate the SOCKADDR_IN structure with the Server IP and Port Number
  3. Connect using the connect function
  4. Send and Recv using the socket
  5. Shutdown and Close when all jobs are done

 

The following sample illustrates the above steps. Only one item missed out here is the usage of recv function.

 

 

#include <winsock2.h>
#include <iostream.h>
int gPort = 8780;
void main()
{
       SOCKET lhSocket;
       SOCKADDR_IN lSockAddr;
       WSADATA wsaData;
       int lConnect;
       int lLength;
       char lData[]="SendData";
       if(WSAStartup(MAKEWORD(2,0),&wsaData) != 0)
       {
            cout<<"Socket Initialization Error. Program aborted\n";
            return;
        }
       lhSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
       if(lhSocket == INVALID_SOCKET)
       {
            cout<<"Invalid Socket "<<GetLastError()<<". Program Aborted\n"<<endl;
        }
       memset(&lSockAddr,0, sizeof(lSockAddr));
       lSockAddr.sin_family = AF_INET;
       lSockAddr.sin_port = htons(gPort);
       lSockAddr.sin_addr.s_addr = inet_addr("IPAddress");
       lConnect = connect(lhSocket,(SOCKADDR *)&lSockAddr,sizeof(SOCKADDR_IN));
       if(lConnect != 0)
       {
             cout<<"Connect Error. Program aborted\n";
             return;
        }
       lLength = send(lhSocket,lData,strlen(lData),0);
       if(lLength < strlen(lData))
       {
            cout<<"Send Error.\n";
       }
       closesocket(lhSocket);
       return;
}


 

Note:
The socket programs in MFC need the library ws2_32.lib to be referenced before linking. Otherwise the VC++ linker throws errors.

 

转载于:https://www.cnblogs.com/lqc1002000/archive/2012/06/19/2555464.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值