示例#1
0
int connect_to(char *serverName, unsigned short severPort){

  int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);                          // Server address
  char *servName = serverName;
  char *servIP = getIPbyHostName(servName, addr);         //Get Server IP by Server Name
  struct sockaddr_in servAddr; 

  // Create socket stream
  memset(&servAddr, 0, sizeof(servAddr));
  servAddr.sin_family = AF_INET;     

  // Convert address
  int rtnVal = inet_pton(AF_INET, servIP, &servAddr.sin_addr.s_addr);
  if (rtnVal == 0){
    printf("inet_pton() failed: invalid address string\n");
  }
  else if (rtnVal < 0){
    printf("inet_pton() failed\n");
  }
  servAddr.sin_port = htons(SERVERPORT);


  // establish connection
  if (connect(sock, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0){
    printf("connect() failed\n");
  }
  return sock;
}
int main(int argc, char *argv[]) {
	FILE * inputFile;
	if (argc < 2 || argc>3) 
		DieWithUserMessage("Parameter(s)","<Server Name> [LClient.txt]");
	if(argc==3)
	{
		inputFile = fopen (argv[2] , "r");
		if (inputFile == NULL)
			DieWithSystemMessage("File Open Error!");
	}
	if(argc==2)
	{
		inputFile =stdin;
	}
	char *servName = argv[1];
	char *servIP=getIPbyHostName(servName, addr);//Get Server IP by Server Name

	FILE *fp;
	if((fp=fopen("LClient.log","w"))==NULL)
		DieWithSystemMessage("File Open Error!");

	//===========Deal with Login Command============
	char _CMDString[MAXLEN_CMD];
	char *CMDString=_CMDString;

	beforeLogin:fputs("Please use login command to connect to the server first as [login <name>]:\n", stdout);

	if(fgets(CMDString,MAXLEN_CMD,inputFile)== NULL)
		DieWithSystemMessage("Input Error!");
	//printf("string length:\t%d\n",strlen(CMDString));
	while((Login(CMDString))!=1)
	{
		fputs("\nLogin again:\n", stdout);
		if(fgets(CMDString,MAXLEN_CMD,inputFile)== NULL)
			DieWithSystemMessage("Input Error!");
	}

	//===========End of dealing with Login Command, and Get the name=========


	//===========initiate the socket =====================	
	in_port_t servPort =atoi("5000");// Set server port (numeric) 5000	
	int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);// Create a reliable, stream socket using TCP
	if (sock < 0)
		DieWithSystemMessage("socket() failed");	
	struct sockaddr_in servAddr;// Construct the server address structure
	memset(&servAddr, 0, sizeof(servAddr)); // Zero out structure
	servAddr.sin_family = AF_INET;			   // IPv4 address family
	// Convert address
	int rtnVal = inet_pton(AF_INET, servIP, &servAddr.sin_addr.s_addr);
	if (rtnVal == 0)
		DieWithUserMessage("inet_pton() failed", "invalid address string");
	else if (rtnVal < 0)
		DieWithSystemMessage("inet_pton() failed");
	servAddr.sin_port = htons(servPort);		// Server port
	//===========END initiate the socket =====================




	//===========Establish the connection to the echo server=============
	if (connect(sock, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0)
		DieWithSystemMessage("connect() failed");
	IsLogined=1;  //Connection Established, and this means someone logined successfully
	char buffer[BUFSIZE];

	int IsListCmd=0;

	//char IsListDone[5]="Done";
	char QUIT[2]="*";
	char _EOF[2]="$";
	int IsReLogin=0;
	for(;;)
	{		
		//puts(CMDString);
		ssize_t numBytes = send(sock, CMDString, strlen(CMDString), 0);
		if (numBytes < 0)
			DieWithSystemMessage("send() failed");
		else if (numBytes != strlen(CMDString))
				DieWithUserMessage("send()", "sent unexpected number of bytes");

		if(IsListCmd==0)
		{
			bufferClean(buffer);
			numBytes = recv(sock, buffer, BUFSIZE - 1, 0);
			if (numBytes < 0)
				DieWithSystemMessage("recv() failed");
			buffer[numBytes] = '\0';// Terminate the string!	
			if(strncmp(buffer,QUIT,1)==0)
			{
				fputs(buffer, fp);
				fputs("\r\n",fp);
				labelQUIT:close(sock);
				goto beforeLogin;
			}

			if(strncmp(buffer,_EOF,1)==0)
			{
				fputs(buffer, fp);
				fputs("\r\n",fp);
				labelEOF:close(sock); 
				if(argc==3)
					fclose(fp);
				fclose(inputFile);
				exit(0);
			}
			if(IsReLogin!=1)
			{
				fputs(buffer, stdout);
				fputs("\n",stdout);
				fputs(buffer, fp);
				fputs("\r\n",fp);
			}
		}
		else
		{	
			int i=0;
			while(IsListCmd==1)
			{
				bufferClean(buffer);
				numBytes = recv(sock, buffer, BUFSIZE - 1, 0);
				if (numBytes < 0)
					DieWithSystemMessage("recv() failed");

				for(i=0;i<strlen(buffer);i++)
				{
					int buffer_Length=strlen(buffer);
					if(buffer[i]=='#')
					{
						buffer[i]='\0';
						fputs(buffer, stdout);
						fputs(buffer, fp);
						/*if(i<buffer_Length)
						{
							i++;
							for(;i<buffer_Length;i++)
							{
								if(buffer[i]=='*')
								{
									puts("QUIT Here!");
									goto labelQUIT;
								}
								if(buffer[i]=='$')
									goto labelEOF;
								fputc(buffer[i],stdout);
								fputc(buffer[i],fp);
							}
						}*/
						IsListCmd=0;
						fputs("\n",stdout);
						//goto ListDone;
						break;
					}
				}
				if(IsListCmd==0)
					break;
				fputs(buffer, stdout);
				fputs(buffer, fp);

			}
		}
		bufferClean(buffer);
		for(;;)
		{
			int IsInputLegal=0;
			bufferClean(CMDString);

//ListDone:
			if(fgets(CMDString,MAXLEN_CMD,inputFile)== NULL)
				DieWithSystemMessage("Input Error!");
			CMDString=trimRight(CMDString);
			//gets(CMDString);    //input another Command
			switch(CommandCheckAndReturncmdCode(CMDString))
			{
				case 1: if(IsLogined==1)
							{
								fputs("You have logined already. Please quit first!\n", stdout);
								IsInputLegal=0;
							} 
							else 
							{
								if(Login(CMDString)==1) 
									IsInputLegal=1;
							}
							break;
				case 2: if(Add(CMDString)==1) IsInputLegal=1; break;
				case 3: if(Remove(CMDString)==1) IsInputLegal=1; break;
				case 4: if(List(CMDString)==1) {IsInputLegal=1;IsListCmd=1;} break;
				case 5: if(Quit(CMDString)==1) {IsInputLegal=1;IsLogined=0;}; break;
				default:IsInputLegal=0;break;
			}
			if(IsInputLegal==1)
				break;
			else
				continue;
		}

	}
	
}