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


// 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("172.18.6.174"); 
	servaddr.sin_port=htons(9990); 
while(true) 
{ 
    r=connect(sHost,(LPSOCKADDR)&servaddr,sizeof(servaddr)); 
 
		if(SOCKET_ERROR==r) 
		{   
			 
			int err =WSAGetLastError(); 
			if(err==WSAEWOULDBLOCK ||err == WSAEINVAL) 
			{ 
			//	Sleep(500); 
				continue; 
			} 
		 
		else if(err==WSAEISCONN) 
		{ 
			break; 
		} 
		else 
		{ 
		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()); 
		while(true) 
		{ 
		r=send(sHost,buf,strlen(buf),0); 
			if(SOCKET_ERROR==r) 
			{   
				int err =WSAGetLastError(); 
				if(err==WSAEWOULDBLOCK) 
				{ 
					Sleep(500); 
					continue; 
				} 
				else 
				{ 
		printf("send failed !\n"); 
		closesocket(sHost); 
		WSACleanup(); 
		return -1; 
				} 
			} 
			break; 
	} 
  while(true) 
  { 
	  	ZeroMemory(buf,maxsize); 
  r=recv(sHost,buf,sizeof(buf)+1,0); 
  if(SOCKET_ERROR==r) 
  { 
	  int err; 
	  err=WSAGetLastError(); 
	  	if(err==WSAEWOULDBLOCK) 
				{ 
					Sleep(100); 
					printf("Waiting for msg"); 
					continue; 
				} 
  else if(err == WSAETIMEDOUT || err == WSAENETDOWN) 
  { 
     printf("recv failed"); 
	  closesocket(sHost); 
	  	WSACleanup(); 
		return -1; 
		} 
  break; 
  } 
  break; 
  } 
  printf("Recv From Server:%s\n",buf); 
  if(strcmp(buf,"quit") == 0) 
  { 
	  printf("quit\n"); 
	  break; 
  } 
	} 
 
 
 
 
 
} 
 
 
 
 
 
 
 
 
 
 
 
 

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