www.pudn.com > chat5.zip > Client.cpp, change:2012-11-08,size:2003b


// chat5.cpp : Defines the entry point for the console application. 
// 
#include "stdafx.h" 
#include<winsock2.h> 
#pragma comment (lib,"ws2_32.lib") 
#include<stdlib.h> 
#include <string> 
#include <iostream> 
#define maxsize 500 
int main(int argc, char* argv[]) 
{ 
   //定义变量 
   WSADATA  wsaData; 
   SOCKET  sHost; 
   SOCKADDR_IN servaddr; 
   char buf[maxsize]; 
   int r; 
  //初始化windows sockets 
	if(WSAStartup(MAKEWORD(2,2),&wsaData)!=0) 
	{ 
		printf("WSAStartup 无法初始化!"); 
		return 0; 
	} 
  //若初始化成功,则显示wsaDATA中的数据 
	printf("Version:%d.%d\n",LOBYTE(wsaData.wVersion),HIBYTE(wsaData.wVersion)); 
    printf("HOGH Version:%d.%d",LOBYTE(wsaData.wHighVersion),HIBYTE(wsaData.wHighVersion)); 
	printf("dESCRIPTION:%s\n",wsaData.szDescription); 
	printf("System Status:%s",wsaData.szSystemStatus); 
  
  //创建用于监听的socket 
	sHost = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); 
	if(INVALID_SOCKET == sHost) 
	{ 
		printf("socket failed !\n"); 
		WSACleanup(); 
		return -1; 
	} 
  //设置服务器地址 
	servaddr.sin_family=AF_INET; 
	servaddr.sin_addr.S_un.S_addr=inet_addr("127.0.0.1"); 
	servaddr.sin_port=htons(9990); 
 
    r=connect(sHost,(LPSOCKADDR)&servaddr,sizeof(servaddr)); 
		if(SOCKET_ERROR==r) 
	{ 
		printf("connect failed !\n"); 
		closesocket(sHost); 
		WSACleanup(); 
		return -1; 
	} 
 
	while(true){ 
		printf("please enter a string to send:"); 
		std::string str; 
		std::getline(std::cin,str); 
		ZeroMemory(buf,maxsize); 
		strcpy(buf,str.c_str()); 
		r=send(sHost,buf,strlen(buf),0); 
			if(SOCKET_ERROR==r) 
	{ 
		printf("send failed !\n"); 
		closesocket(sHost); 
		WSACleanup(); 
		return -1; 
	} 
  r=recv(sHost,buf,sizeof(buf+1),0); 
  printf("recv from server: %s\n",buf); 
	if(strcmp(buf,"quit")==0) 
	{ 
	printf("quit\n"); 
		break; 
	} 
 
	} 
 
  closesocket(sHost); 
		WSACleanup(); 
		system("pause"); 
		return 0; 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
} 

2018无需申请注册送58体验金