#include "stdafx.h"
#include <WINSOCK2.H>
#include <string>
#include <iostream>
#pragma comment(lib,"WS2_32.lib")
#define BUF_SIZE 64
int _tmain(int argc, _TCHAR* argv[])
{
WSADATAwsd;
SOCKETsHost;
SOCKADDR_INservAddr;
charbuf[BUF_SIZE];
intretVal;
//初始化Socket动态库
if(WSAStartup(MAKEWORD(2,2),&wsd)!= 0){
printf("WSAStartupfailed !\n");
return1;
}
//创建用于通信的Socket
sHost= socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(INVALID_SOCKET== sHost){
printf("socketfailed !\n");
WSACleanup();
return-1;
}
//设置服务器Socket地址
servAddr.sin_family= AF_INET;
//用户根据实际情况更改IP地址
servAddr.sin_addr.S_un.S_addr= inet_addr("127.0.0.1");
//在实际应用中,建议将服务器的IP地址和端口号保存在配置文件中
servAddr.sin_port= htons(9990);
//计算地址的长度
intsServerAddlen = sizeof(servAddr);
//连接服务器
retVal= connect(sHost,(LPSOCKADDR)&servAddr,sizeof(servAddr));
if(SOCKET_ERROR== retVal){
printf("connectfailed !\n");
closesocket(sHost);
WSACleanup();
return-1;
}
//循环向服务器发送字符串,并显示反馈信息
//发送“quit”将使服务器程序退出,同时客户端程序自身也将退出
while(true){
//向服务器发送数据
printf("Pleaseinput a string to send: ");
std::stringstr;
//接收输入的数据
std::getline(std::cin,str);
//将用户输入的数据复制到buf中
ZeroMemory(buf,BUF_SIZE);
strcpy(buf,str.c_str());
//向服务器发送数据
retVal= send(sHost,buf,strlen(buf),0);
if(SOCKET_ERROR== retVal){
printf("sendfialed !\n");
closesocket(sHost);
WSACleanup();
return-1;
}
//接收服务器回传的数据
retVal= recv(sHost,buf,sizeof(buf)+1,0);
printf("RecvFrom Server: %s\n",buf);
//如果收到“quit”则退出
if(strcmp(buf,"quit")== 0){
printf("quit!\n");
break;
}
}
//释放资源
closesocket(sHost);
WSACleanup();
//暂停,按任意键继续
system("pause");
return0;
}
![](http://hi.csdn.net/attachment/201109/25/0_1316951150AJ6y.gif)
![](http://hi.csdn.net/attachment/201109/25/0_13169511559S51.gif)
![](http://hi.csdn.net/attachment/201109/25/0_1316951161I9B6.gif)