循序渐进学unix——上机记录(七),socket

本次的主题是基本网络编程:socket,涉及到的概念比较多,就不详细展开了。从编程角度简单的说,为了在客户端和服务器之间建立一个连接,服务器端需要依次调用这些函数:

  1. socket,获得一个socket
  2. bind,将获得的socket绑定到指定的地址和端口
  3. listen,让此socket进入等待状态,等待客户端的连接
  4. accept,当建立起与客户端之间的连接时,此函数返回代表此连接的socket。即类似于文件描述符,我们可以把客户端看作文件,向网络上进行读写操作,从而完成通信过程。
客户端需要调用的函数:
  1. socket
  2. connect,向指定地址的服务器的指定端口发起连接
服务器和客户端都需用到的通信函数:
  1. send
  2. recv
详细信息和函数方法等就不赘述了,请参见man 文档。

下面来看几道练习。
1. 从客户端把用户输入的信息发送到服务器,直到用户输入“over”。这是一道基础题,直接上代码了。
server:
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
	int numPort, lenMsg, i;
	int sockServ, sockClient;
	struct sockaddr_in adrServ, adrClient;
	char message[256];
	char * overMsg = "over";
	int adrSize = sizeof(adrClient);
	int yes = 1;

	if(argc < 2)
	{
		printf("syntaxe : %s numPort\n", argv[0]);
		return -1;
	}
	

	//set local addr and port
	numPort = atoi(argv[1]);
	adrServ.sin_addr.s_addr = INADDR_ANY;
	adrServ.sin_family = AF_INET;
	adrServ.sin_port = htons(numPort);
	bzero(&(adrServ.sin_zero), 8) ;
	
	//Get a socket
	if((sockServ = socket(PF_INET, SOCK_STREAM, 0)) == -1) { perror("sockServet"); return -1; }
	
	//We can set some param here.// paramètrage de la socket pour réutiliser le N° ce port sans délai
	if(setsockopt(sockServ, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); return -1; }

	// bind
	if(bind(sockServ, (struct sockaddr *)(&adrServ), sizeof(adrServ)) == -1) { perror("bind"); return -1; }

	// place la socket en écoute
	if(listen(sockServ, 1) == -1) { perror("listen"); return -1; }
	

	// wait for a connection from a client
	if((sockClient = accept(sockServ, (struct sockaddr *)(&adrClient), &adrSize)) == -1) { perror("accept"); return -1; }
	printf("New socket client : %s\n", inet_ntoa(adrClient.sin_addr));
	do
	{
		// Read a msg from client
		if((lenMsg = recv(sockClient, message, 256, 0)) == -1)
		{ perror("recv"); return -1; }
		message[lenMsg] = '\0';
		printf("New msg received : %s\n", message);
		//printf("New msg received : %s, %d\n", message, strcmp(message, overMsg));
		
	}while(strcmp(message, overMsg) != 0);	
	// fermeture de la connexion
	close(sockServ);
	
	return 0;
}


client:
#include<stdio.h>
#include<stdlib.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/socket.h>
#include<string.h>
void main(int argc, char* argv[])
{
	if(argc < 3)
	{
		printf("Syntax:%s server_addr <portNum>\n", argv[0]);
		exit(0);
	}


	int fdSock;
	//get a socket
	if( (fdSock=socket(AF_INET, SOCK_STREAM, 0)) == -1){perror("socket"); exit(1);}
	
	//config the address of the server to connect
	struct sockaddr_in addrServer;
	addrServer.sin_family = AF_INET;//Address family
	inet_pton(AF_INET, argv[1], &(addrServer.sin_addr));//Convert the addr from "presentation" to "numeric"
	addrServer.sin_port=htons(atoi(argv[2]));//set the port number
	//Connect to server
	if( connect( fdSock, (struct sockaddr *)(&addrServer), sizeof(addrServer))== -1){perror("connect"); exit(1);}
	
	char buf[1024];
	gets(buf);//get a msg from terminal
	while(buf[0] != '\0')
	{
		printf("Gets gets : %s\n", buf);
		//Send the msg to server. See also "sendto" and "sendmsg"
		if( send(fdSock, buf, strlen(buf), 0) == -1){perror("Send"); exit(1);}
		if(strcmp(buf, "over") == 0)
		{
			printf("Exit...\n");
			close(fdSock);
			exit(0);
		}
		gets(buf);
	}


}
运行结果:
client:
administrateur@ordicentre:~/Bureau/POLYTECH/unix/TD UNIX2012/td6$ ./client12 127.0.0.1 9999
hello
Gets gets : hello
byebye
Gets gets : byebye
over
Gets gets : over
Exit...
administrateur@ordicentre:~/Bureau/POLYTECH/unix/TD UNIX2012/td6$ 

server:
administrateur@ordicentre:~/Bureau/POLYTECH/unix/TD UNIX2012/td6$ ./server12 9999
New socket client : 127.0.0.1
New msg received : hello
New msg received : byebye
New msg received : over
administrateur@ordicentre:~/Bureau/POLYTECH/unix/TD UNIX2012/td6$ 




2. 这次结合上exec,从客户端发送命令到服务器,服务器在本地执行命令。
server:
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>

#define MAX_NUM_ARG 10
void exeCmd(char * cmd);

int main(int argc, char *argv[])
{
	int numPort, lenMsg, i;
	int sockServ, sockClient;
	struct sockaddr_in adrServ, adrClient;
	char message[256];
	char * overMsg = "over";
	int adrSize = sizeof(adrClient);
	int yes = 1;

	if(argc < 2)
	{
		printf("syntaxe : %s numPort\n", argv[0]);
		return -1;
	}
	

	//set local addr and port
	numPort = atoi(argv[1]);
	adrServ.sin_addr.s_addr = INADDR_ANY;
	adrServ.sin_family = AF_INET;
	adrServ.sin_port = htons(numPort);
	bzero(&(adrServ.sin_zero), 8) ;
	
	//Get a socket
	if((sockServ = socket(PF_INET, SOCK_STREAM, 0)) == -1) { perror("sockServet"); return -1; }
	
	//We can set some param here.// paramètrage de la socket pour réutiliser le N° ce port sans délai
	if(setsockopt(sockServ, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); return -1; }

	// bind
	if(bind(sockServ, (struct sockaddr *)(&adrServ), sizeof(adrServ)) == -1) { perror("bind"); return -1; }

	// place la socket en écoute
	if(listen(sockServ, 1) == -1) { perror("listen"); return -1; }
	

	// wait for a connection from a client
	if((sockClient = accept(sockServ, (struct sockaddr *)(&adrClient), &adrSize)) == -1) { perror("accept"); return -1; }
	printf("New socket client : %s\n", inet_ntoa(adrClient.sin_addr));
	do
	{
		// Read a cmd from client
		if((lenMsg = recv(sockClient, message, 256, 0)) == -1)
			{ perror("recv"); return -1; }
		message[lenMsg] = '\0';
		printf("\nNew cmd received : %s, result:\n", message);
		exeCmd(message);
		//printf("New msg received : %s, %d\n", message, strcmp(message, overMsg));
		
	}while(strcmp(message, overMsg) != 0);	
	// fermeture de la connexion
	close(sockServ);
	
	return 0;
}


void exeCmd(char * cmd)
{
	if(fork()==0)
	{
		char *argv[MAX_NUM_ARG] = {NULL};
		int i;
		char *arg;
		for(i=0; i<MAX_NUM_ARG; i++)
		{
			if(i>0) cmd = NULL;
			arg = strtok(cmd, " ");
			if(arg != NULL)
			{
				//put this arg into argv[]
				argv[i] = calloc( sizeof(char), strlen(arg+1)) ;
				strcpy(argv[i], arg);
			}
			else
			{//execute this cmd
				execvp(argv[0], argv);
				exit(0);
			}
			
		}
		exit(0);
	}
}

client:
#include<stdio.h>
#include<stdlib.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/socket.h>
#include<string.h>
void main(int argc, char* argv[])
{
	if(argc < 3)
	{
		printf("Syntax:%s server_addr <portNum>\n", argv[0]);
		exit(0);
	}

	int fdSock;
	//get a socket
	if( (fdSock=socket(AF_INET, SOCK_STREAM, 0)) == -1){perror("socket"); exit(1);}
	
	//config the address of the server to connect
	struct sockaddr_in addrServer;
	addrServer.sin_family = AF_INET;//Address family
	inet_pton(AF_INET, argv[1], &(addrServer.sin_addr));//Convert the addr from "presentation" to "numeric"
	addrServer.sin_port=htons(atoi(argv[2]));//set the port number
	//Connect to server
	if( connect( fdSock, (struct sockaddr *)(&addrServer), sizeof(addrServer))== -1){perror("connect"); exit(1);}
	
	char buf[1024];
	printf("\nexcute_cmd_in_distance$");
	gets(buf);//get a cmd from terminal
	while(buf[0] != '\0')
	{
		//printf("Gets gets : %s\n", buf);
		//Send the msg to server. See also "sendto" and "sendmsg"
		if( send(fdSock, buf, strlen(buf), 0) == -1){perror("Send"); exit(1);}
		if(strcmp(buf, "over") == 0)
		{
			printf("Exit...\n");
			close(fdSock);
			exit(0);
		}
		printf("\nexcute_cmd_in_distance$");
		gets(buf);
	}

}

运行结果:
client:
administrateur@ordicentre:~/Bureau/POLYTECH/unix/TD UNIX2012/td6$ ./client3 127.0.0.1 9999

excute_cmd_in_distance$ls

excute_cmd_in_distance$ls -l

excute_cmd_in_distance$pwd

excute_cmd_in_distance$over
Exit...
administrateur@ordicentre:~/Bureau/POLYTECH/unix/TD UNIX2012/td6$ 

server:
administrateur@ordicentre:~/Bureau/POLYTECH/unix/TD UNIX2012/td6$ ./server3 9999
New socket client : 127.0.0.1

New cmd received : ls, result:
12_client.c  3_client.c  client   client12  in.h      server3    td6-1_serveur-modif.c  types.h
12_server.c  3_server.c  client1  client3   server12  socket.h    td6.pdf

New cmd received : ls -l, result:
total 152
-rw-r--r-- 1 administrateur administrateur  1171 déc.  26 12:39 12_client.c
-rw-r--r-- 1 administrateur administrateur  1842 déc.  26 12:36 12_server.c
-rw-r--r-- 1 administrateur administrateur  1250 déc.  26 13:28 3_client.c
-rw-r--r-- 1 administrateur administrateur  2323 déc.  26 13:28 3_server.c
-rw-r--r-- 1 administrateur administrateur  7563 déc.   5 15:17 client
-rwxrwxr-x 1 administrateur administrateur  7549 déc.  26 11:47 client1
-rwxrwxr-x 1 administrateur administrateur  7623 déc.  26 12:31 client12
-rwxrwxr-x 1 administrateur administrateur  7622 déc.  26 13:28 client3
-rw-r--r-- 1 administrateur administrateur 18637 janv. 22  2011 in.h
-rwxrwxr-x 1 administrateur administrateur  7668 déc.  26 12:36 server12
-rwxrwxr-x 1 administrateur administrateur  7914 déc.  26 13:28 server3
-rw-r--r-- 1 administrateur administrateur  9597 janv. 22  2011 socket.h
-rw-r--r-- 1 administrateur administrateur  1953 déc.  26 11:46 td6-1_serveur-modif.c
-rw-r--r-- 1 administrateur administrateur 44356 nov.  30 15:39 td6.pdf
-rw-r--r-- 1 administrateur administrateur  6838 janv. 22  2011 types.h

New cmd received : pwd, result:
/home/administrateur/Bureau/POLYTECH/unix/TD UNIX2012/td6

New cmd received : over, result:
administrateur@ordicentre:~/Bureau/POLYTECH/unix/TD UNIX2012/td6$ 



3. 理解”一切皆文件“的概念。将server的标准输入输出重定向到client,即从client读取命令字符串,并将执行结果返回给client输出。到这里不难发现我们所要做的有点像个远程终端。
并无特殊,加上重定向(在执行命令的子进程中)即可。
server:
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>

#define MAX_NUM_ARG 10
void exeCmd(int sockClient, char * cmd)
{
	
	if(fork()==0)
	{
		//Set redirection
		dup2(sockClient, 0);
		dup2(sockClient, 1);
		close(sockClient);

		char *argv[MAX_NUM_ARG] = {NULL};
		int i;
		char *arg;
		for(i=0; i<MAX_NUM_ARG; i++)
		{
			if(i>0) cmd = NULL;
			arg = strtok(cmd, " ");
			if(arg != NULL)
			{
				//put this arg into argv[]
				//argv[i] = calloc( sizeof(char), strlen(arg+1)) ;
				//strcpy(argv[i], arg);
				argv[i] = arg;//We can also simply do like this.
				fprintf(stderr, "cmd[%d] = %s\n",i,arg);
			}
			else
			{//execute this cmd
				execvp(argv[0], argv);
				exit(0);
			}
			
		}
		exit(0);
	}
}

int main(int argc, char *argv[])
{
	

	int numPort, lenMsg, i;
	int sockServ, sockClient;
	struct sockaddr_in adrServ, adrClient;
	char message[256];
	char * overMsg = "over";
	int adrSize = sizeof(adrClient);
	int yes = 1;

	if(argc < 2)
	{
		printf("syntaxe : %s numPort\n", argv[0]);
		return -1;
	}
	

	//set local addr and port
	numPort = atoi(argv[1]);
	adrServ.sin_addr.s_addr = INADDR_ANY;
	adrServ.sin_family = AF_INET;
	adrServ.sin_port = htons(numPort);
	bzero(&(adrServ.sin_zero), 8) ;
	
	//Get a socket
	if((sockServ = socket(PF_INET, SOCK_STREAM, 0)) == -1) { perror("sockServet"); return -1; }
	
	//We can set some param here.// paramètrage de la socket pour réutiliser le N° ce port sans délai
	if(setsockopt(sockServ, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); return -1; }

	// bind
	if(bind(sockServ, (struct sockaddr *)(&adrServ), sizeof(adrServ)) == -1) { perror("bind"); return -1; }

	// place la socket en écoute
	if(listen(sockServ, 1) == -1) { perror("listen"); return -1; }
	

	// wait for a connection from a client
	if((sockClient = accept(sockServ, (struct sockaddr *)(&adrClient), &adrSize)) == -1) { perror("accept"); return -1; }
	printf("New socket client : %s\n", inet_ntoa(adrClient.sin_addr));

	do
	{
		// Read a cmd from client
		//fgets(stdin, message);
		//fscanf(sockClient,"%s",message);
		if((lenMsg = recv(sockClient, message, 256, 0)) == -1)
			{ perror("recv"); return -1; }
		else if (lenMsg == 0)
		{
			close(sockClient);
			return 0;
		}
		message[lenMsg] = '\0';
		printf("New cmd received : %s\n", message);
		exeCmd(sockClient, message);
		//fflush(sockClient);
		//printf("New msg received : %s, %d\n", message, strcmp(message, overMsg));
		
	}while(strcmp(message, overMsg) != 0);	
	// fermeture de la connexion
	close(sockClient);
	
	return 0;
}
server运行结果:
administrateur@ordicentre:~/Bureau/POLYTECH/unix/TD UNIX2012/td6$ ./server4 9999
New socket client : 127.0.0.1
New cmd received : ls
cmd[0] = ls
New cmd received : pwd
cmd[0] = pwd
New cmd received : date
cmd[0] = date
New cmd received : ls -l
cmd[0] = ls
cmd[1] = -l
New cmd received : over
administrateur@ordicentre:~/Bureau/POLYTECH/unix/TD UNIX2012/td6$ cmd[0] = over

client:
#include<stdio.h>
#include<stdlib.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/socket.h>
#include<string.h>
void main(int argc, char* argv[])
{
	if(argc < 3)
	{
		printf("Syntax:%s server_addr <portNum>\n", argv[0]);
		exit(0);
	}

	int fdSock, res;
	//get a socket
	if( (fdSock=socket(AF_INET, SOCK_STREAM, 0)) == -1){perror("socket"); exit(1);}
	
	//config the address of the server to connect
	struct sockaddr_in addrServer;
	addrServer.sin_family = AF_INET;//Address family
	inet_pton(AF_INET, argv[1], &(addrServer.sin_addr));//Convert the addr from "presentation" to "numeric"
	addrServer.sin_port=htons(atoi(argv[2]));//set the port number
	//Connect to server
	if( connect( fdSock, (struct sockaddr *)(&addrServer), sizeof(addrServer))== -1){perror("connect"); exit(1);}
	
	char buf[1024];
	printf("\nexcute_cmd_in_distance$");
	gets(buf);//get a cmd from terminal
	while(buf[0] != '\0')
	{
		//printf("Gets gets : %s\n", buf);
		//Send the msg to server. See also "sendto" and "sendmsg"
		if( send(fdSock, buf, strlen(buf), 0) == -1){perror("Send"); exit(1);}
		if(strcmp(buf, "over") == 0)
		{
			printf("Exit...\n");
			close(fdSock);
			exit(0);
		}
		if( (res = recv(fdSock, buf, 1024, 0)) == -1){perror("recv"); exit(1);}
		else if(res == 0) {close(fdSock); exit(0);}
		else
		{
			buf[res] = '\0';
			printf("\n%s",buf);
		}
		printf("\nexcute_cmd_in_distance$");
		gets(buf);
	}

}

client运行结果:
/home/administrateur/Bureau/POLYTECH/unix/TD UNIX2012/td6

excute_cmd_in_distance$date

mercredi 26 décembre 2012, 17:10:46 (UTC+0100)

excute_cmd_in_distance$ls -l

total 88
-rw-r--r-- 1 administrateur administrateur  1171 déc.  26 12:39 12_client.c
-rw-r--r-- 1 administrateur administrateur  1842 déc.  26 12:36 12_server.c
-rw-r--r-- 1 administrateur administrateur  1250 déc.  26 13:28 3_client.c
-rw-r--r-- 1 administrateur administrateur  2323 déc.  26 13:28 3_server.c
-rw-r--r-- 1 administrateur administrateur  1433 déc.  26 17:10 4_client.c
-rw-r--r-- 1 administrateur administrateur  2626 déc.  26 17:06 4_server.c
-rwxrwxr-x 1 administrateur administrateur  7658 déc.  26 17:10 client4
drwxrwxr-x 2 administrateur administrateur  4096 déc.  26 14:54 doc
-rwxrwxr-x 1 administrateur administrateur  7947 déc.  26 17:10 server4
-rw-r--r-- 1 administrateur administrateur 44356 nov.  30 15:39 td6.pdf

excute_cmd_in_distance$over
Exit...
administrateur@ordicentre:~/Bureau/POLYTECH/unix/TD UNIX2012/td6$ 

5. 在第4题的基础上,我们考虑I/O多路复用。试想,当client发送完命令,并且正在等待执行结果的时候,用户又在终端输入了一条命令。由于程序被recv阻塞,用户输入的命令并不会被处理。有没有一种方法可以监听所有的io操作,并在任何一个操作结束阻塞的时候通知我们呢?没错,我们在谈select和poll函数。下面的实现使用了poll函数,请注意看它是如何同时监听所有io并在任何一个io操作准备就绪时返回的。
client:
#include<stdio.h>
#include<stdlib.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/socket.h>
#include<string.h>
#include<poll.h>
void main(int argc, char* argv[])
{
	if(argc < 3)
	{
		printf("Syntax:%s server_addr <portNum>\n", argv[0]);
		exit(0);
	}

	int fdSock, res, nready;
	//get a socket
	if( (fdSock=socket(AF_INET, SOCK_STREAM, 0)) == -1){perror("socket"); exit(1);}
	
	//config the address of the server to connect
	struct sockaddr_in addrServer;
	addrServer.sin_family = AF_INET;//Address family
	inet_pton(AF_INET, argv[1], &(addrServer.sin_addr));//Convert the addr from "presentation" to "numeric"
	addrServer.sin_port=htons(atoi(argv[2]));//set the port number
	//Connect to server
	if( connect( fdSock, (struct sockaddr *)(&addrServer), sizeof(addrServer))== -1){perror("connect"); exit(1);}
	
	char buf[1024];
	printf("\nexcute_cmd_in_distance$");
	//gets(buf);//get a cmd from terminal
	
	//POLL added here
	struct pollfd pfds[2];
	bzero(pfds, sizeof(pfds[0]));	
	bzero(pfds+1, sizeof(pfds[0]));
	pfds[0].fd = 0;
	pfds[0].events = POLLRDNORM;//The event waited.(Normal read)

	pfds[1].fd = fdSock;
	pfds[1].events = POLLRDNORM;
	
	while(buf[0] != '\0')
	{
		printf("\nexcute_cmd_in_distance$");
		nready = poll(pfds, 2, -1);//nready is the number of ready fds
		if(pfds[0].revents & POLLRDNORM)
		{
			//deal with user input, send cmd to server
			gets(buf);
			if( send(fdSock, buf, strlen(buf), 0) == -1){perror("Send"); exit(1);}
			if(strcmp(buf, "over") == 0)
			{
				printf("Exit...\n");
				close(fdSock);
				exit(0);
			}
			
			pfds[0].revents = 0;
			nready --;
			if(nready == 0)
				continue;
		}
		if(pfds[1].revents & POLLRDNORM )
		{
			//deal with socket, display the result of the last cmd
			pfds[1].revents = 0;
				
			if( (res = recv(fdSock, buf, 1024, 0)) == -1){perror("recv"); exit(1);}
			else if(res == 0) {close(fdSock); exit(0);}
			else
			{
				buf[res] = '\0';
				printf("\n%s",buf);
			}
		}
		
	}

}

server:代码无太大变化,除了exeCmd函数。现在我们使用”bash“命令来执行其它命令。
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>

#define MAX_NUM_ARG 10
void exeCmd(int sockClient, char * cmd)
{
	
	if(fork()==0)
	{
		//Set redirection
		dup2(sockClient, 0);
		dup2(sockClient, 1);
		close(sockClient);

		execlp("bash", "bash", "-c", cmd, NULL);
		exit(0);
	}
}

int main(int argc, char *argv[])
{
	

	int numPort, lenMsg, i;
	int sockServ, sockClient;
	struct sockaddr_in adrServ, adrClient;
	char message[256];
	char * overMsg = "over";
	int adrSize = sizeof(adrClient);
	int yes = 1;

	if(argc < 2)
	{
		printf("syntaxe : %s numPort\n", argv[0]);
		return -1;
	}
	

	//set local addr and port
	numPort = atoi(argv[1]);
	adrServ.sin_addr.s_addr = INADDR_ANY;
	adrServ.sin_family = AF_INET;
	adrServ.sin_port = htons(numPort);
	bzero(&(adrServ.sin_zero), 8) ;
	
	//Get a socket
	if((sockServ = socket(PF_INET, SOCK_STREAM, 0)) == -1) { perror("sockServet"); return -1; }
	
	//We can set some param here.// paramètrage de la socket pour réutiliser le N° ce port sans délai
	if(setsockopt(sockServ, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); return -1; }

	// bind
	if(bind(sockServ, (struct sockaddr *)(&adrServ), sizeof(adrServ)) == -1) { perror("bind"); return -1; }

	// place la socket en écoute
	if(listen(sockServ, 1) == -1) { perror("listen"); return -1; }
	

	// wait for a connection from a client
	if((sockClient = accept(sockServ, (struct sockaddr *)(&adrClient), &adrSize)) == -1) { perror("accept"); return -1; }
	printf("New socket client : %s\n", inet_ntoa(adrClient.sin_addr));

	
	do
	{
		if((lenMsg = recv(sockClient, message, 256, 0)) == -1)
			{ perror("recv"); return -1; }
		else if (lenMsg == 0)
		{
			close(sockClient);
			return 0;
		}
		message[lenMsg] = '\0';
		printf("New cmd received : %s\n", message);
		exeCmd(sockClient, message);
		
	}while(strcmp(message, overMsg) != 0);	
	// fermeture de la connexion
	close(sockClient);
	
	return 0;
}

运行结果:
client:每条命令下显示的结果其实是在server端执行的。你发现什么变化没有?当我们执行find / -name "socket.h" 这条耗时的命令后,server端并不能马上返回结果,而我们仍可以马上执行下一条命令:date,并且我们先得到了date的结果,之后才是find命令的搜索结果。
administrateur@ordicentre:~/Bureau/POLYTECH/unix/TD UNIX2012/td6$ ./4_client 127.0.0.1 9999

ls
excute_cmd_in_distance$
12_client.c
12_server.c
3_client.c
3_server.c
4
4_client
4_client.c
4_poll_client.c
4_poll_client.c~
4_poll_server.c
4_poll_server.c~
4_server.c
4_server.c~
client4
clientPoll
doc
server4
td6.pdf

sudo find / -name "socket.h"
excute_cmd_in_distance$date

mercredi 26 décembre 2012, 17:53:30 (UTC+0100)

excute_cmd_in_distance$
/media/DONNEES/Polytech/Tutorial/Linux/linux-2.6.33.20/linux-2.6.33.20/arch/alpha/include/asm/socket.h
/media/DONNEES/Polytech/Tutorial/Linux/linux-2.6.33.20/linux-2.6.33.20/arch/arm/include/asm/socket.h
/media/DONNEES/Polytech/Tutorial/Linux/linux-2.6.33.20/linux-2.6.33.20/arch/avr32/include/asm/socket.h
/media/DONNEES/Polytech/Tutorial/Linux/linux-2.6.33.20/linux-2.6.33.20/arch/blackfin/include/asm/socket.h
/media/DONNEES/Polytech/Tutorial/Linux/linux-2.6.33.20/linux-2.6.33.20/arch/cris/include/asm/socket.h
/media/DONNEES/Polytech/Tutorial/Linux/linux-2.6.33.20/linux-2.6.33.20/arch/frv/include/asm/socket.h
/media/DONNEES/Polytech/Tutorial/Linux/linux-2.6.33.20/linux-2.6.33.20/arch/h8300/include/asm/socket.h
/media/DONNEES/Polytech/Tutorial/Linux/linux-2.6.33.20/linux-2.6.33.20/arch/ia64/include/asm/socket.h
/media/DONNEES/Polytech/Tutorial/Linux/linux-2.6.33.20/linux-2.6.33.20/arch/m32r/include/asm/socket.h
/media/DONNEES/Polytech/Tutorial/Linux/linux-2.6.33.20/linux-2.6.33.20/arch/m68k/include/asm/socket.h
excute_cmd_in_distance$

server:
administrateur@ordicentre:~/Bureau/POLYTECH/unix/TD UNIX2012/td6$ ./4
syntaxe : ./4 numPort
administrateur@ordicentre:~/Bureau/POLYTECH/unix/TD UNIX2012/td6$ ./4 9999
New socket client : 127.0.0.1
New cmd received : ls
New cmd received : sudo find / -name "socket.h"
[sudo] password for administrateur: 
New cmd received : date

可以看出server先后收到的所有命令。另外,由于重定向是在子进程中做得,所以要求输入密码的那行并没有发送给客户端而是在本地显示了。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值