|
在下有一道难题想请版主大侠或高手指教!!谢谢!!
题目要求是:在LINUX下实现多用户访问服务器的程序.
下面第一个是服务器端(server.c)的程序,第二个是客户端(client.c);但我编的这个只能实现一个用户来访问服务器的功能,所以还请哪们高手帮着看看:应如何修改才能实现多用户访问服务器的功能.谢谢......
服务器端(SERVER.C)
#include<sys/socket.h>
#include<sys/types.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<netdb.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<sys/select.h>
#include<sys/ioctl.h>
#include<errno.h>
#include<signal.h>
main()
{
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(0,&rfds);
char buf[100];
int listener=socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in svr_addr;
bzero((void*)&svr_addr, sizeof(svr_addr));
svr_addr.sin_family=AF_INET;
svr_addr.sin_port=htons(12345);
svr_addr.sin_addr.s_addr=INADDR_ANY;
bind(listener, (struct sockaddr*)&svr_addr, sizeof(svr_addr));
listen(listener, 10);
puts("server started\r\n");
struct sockaddr_in cli_addr;
socklen_t len=sizeof(cli_addr);
int cli_fd=accept(listener, (struct sockaddr*)&cli_addr, &len);
FD_SET(cli_fd,&rfds);
while(1)
{
FD_SET(0,&rfds);
FD_SET(cli_fd,&rfds);
select(cli_fd+1,&rfds,0,0,0);
if(FD_ISSET(0,&rfds)){
ssize_t count=read(0,buf,sizeof(buf));
send(cli_fd,buf,count,0);
}
if(FD_ISSET(cli_fd,&rfds)){
int count=recv(cli_fd,buf,sizeof(buf),0);
if(count<=0)break;
write(1,buf,count);
}
}
close(cli_fd);
close(listener);
客户端(client.c)
#include<sys/socket.h>
#include<sys/types.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/select.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<netdb.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<sys/select.h>
#include<sys/ioctl.h>
#include<errno.h>
#include<signal.h>
main()
{
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(0,&rfds);
char buf[100];
int client = socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in svr_addr;
bzero((void *) &svr_addr, sizeof(svr_addr));
svr_addr.sin_family = AF_INET;
svr_addr.sin_port = htons(12345);
svr_addr.sin_addr.s_addr = inet_addr("xxx.xxx.xxx.xxx");
connect(client, (struct sockaddr *) &svr_addr, sizeof(svr_addr));
FD_SET(client,&rfds);
while (1)
{
FD_SET(client,&rfds);
FD_SET(0,&rfds);
select(client+1,&rfds,NULL,NULL,NULL);
if(FD_ISSET(0,&rfds)){
ssize_t count=read(0,buf,sizeof(buf));
send(client,buf,count,0);
}
if(FD_ISSET(client,&rfds)){
int count=recv(client,buf,sizeof(buf),0);
if(count<=0)break;
write(1,buf,count);
}
}
close(client);
} |
|