【发布时间】:2016-09-23 14:07:04
【问题描述】:
我有一个回显服务器和三个客户端,我需要的是每个客户端都可以向服务器发送数据,并且每个数据都打印在服务器的三个不同的终端中。
我想知道这是否可行,以及我需要使用哪些附加功能才能做到这一点。我只需要了解我可以使用哪些元素来得到我想要的。
我正在使用 C 语言和四台装有 CentOS 的计算机。这是我的两个程序的代码(我省略了错误处理代码):
客户端程序:
int main(int argc, char *argv[])
{
int clientSocket,remotePort,status=0;
struct sockaddr_in ServerName={0};
char buffer[256]="";
char *remoteHost=NULL;
remoteHost=argv[1];
remotePort=atoi(argv[2]);
clientSocket= socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
ServerName.sin_family=AF_INET;
ServerName.sin_port=htons(remotePort);
ServerName.sin_addr.s_addr=inet_addr=(remoteHost);
status=connect(clientSocket,(struct sockaddr *)&ServerName,sizeof(ServerName));
while(strcmp(buffer,"exit"))
{
scanf("%s",buffer);
write(clientSocket,buffer,strlen(buffer));
read(clientSocket,buffer,sizeof(buffer));
printf("%s\n",buffer);
}
}
服务器程序:
#define BACK_LOG 5
int main(int argc, char *argv[])
{
int serverSocket=0,status=0,clientSocket=0,longitud=0,port;
char buffer[256]="";
struct sockaddr_in serverName,clientName;
buffer[0]='\0';
port=atoi(argv[1]);
serverSocket=socket(AF_INET,SOCK_STREAM,0);
serverName.sin_family=AF_INET;
serverName.sin_port=htons(port);
serverName.sin_addr.s_addr=htonl(INADDR_ANY);
status=bind(serverSocket,(struct sockaddr *)&serverName, sizeof(serverName));
status=listen(serverSocket,BACK_LOG);
int clientLength = sizeof(clientName);
clientSocket=accept(serverSocket,(struct sockaddr *)&clientName, &clientLength);
while(read(clientSocket,buffer,sizeof(buffer))!=0)
{
longitud=strlen(buffer);
printf("%s %i\n",buffer,strlen(buffer));
write(clientSocket,buffer,longitud);
strncpy(buffer,buffer,longitud+1);
}
close(serverSocket);
}
【问题讨论】:
-
查找
select系统调用。 -
谢谢,我找到了两个选项:使用
select和使用threads和pthread,是在我的回显服务器中处理多个连接的好方法。