这是在CSDN上一网友贴出来的一小程序,用C语言实现,采用了多路I/O复用的方式实现并发服务器的功能.
一个服务器接收多个客户端的连接请求,某客户端发出向服务器发送的数据,服务器接收后都转发到其它的客户端,服务器不参与聊天的工作,只是完成了信息的转发功能.
哎,新浪的编辑器总是把C语言的注释代码给过滤掉,有点不爽!
//这是一本数上的例子,和你的功能一样.你的例子要改动的太大,偷懒一下.,下边一共5个文件,你弄好后,直接make就可以了,再把config内的ip和端口改一下运行就可以了
//采取的方式是这样的:server只起个中转作用,多clent连接上后,多个clent可以通过server交谈,server本身不参与交谈.
//用法:在一个终端或则后天提交server后,
//在多个终端分别运行clent交谈即可.
//------------------------------------server.c-----------------------------------------
#include
#include
#include "inet.h"
int init_ser( int);
int max( int
a, int b)
{
int themax;
if ( a
> b) themax = a;
else themax
= b;
return
themax;
}
void set_name( char *line, char *name)
{
strcpy(
name, &line[1]);
sprintf(
line, "%s join the roomn", name);
}
void add_name( char *line, char *name)
{
char theline[MAX_LINE];
strcpy(
theline, name);
strcat(
theline, " : ");
strcat(
theline, line);
strcpy(
line, theline);
}
int user_free( int user_link[MAX_CLIENT])
{
int i = 0;
while ( ( user_link[i] != 0)&&( i
if ( i == MAX_CLIENT) return( -1);
return( i);
}
void add_sockset( fd_set *sockset, int sockfd, int *user_link, int
*userfd)
{
int i;
FD_ZERO(
sockset);
FD_SET(
sockfd, sockset);
for ( i=0; i
if ( user_link[i] == 1) {
FD_SET( userfd[i], sockset);
}
}
}
int main(
void)
{
int sockfd;
int new_sockfd;
int user_link[MAX_CLIENT];
int userfd[MAX_CLIENT];
char username[MAX_CLIENT][MAX_NAME];
char line[MAX_LINE];
int userCount;
unsigned int cli_len;
struct sockaddr_in cli_addr;
FILE *file;
int port;
int length,
i, j;
fd_set sockset;
int maxfd =
0;
file =
fopen( "config", "r");
fgets( line,
MAX_LINE, file);
fscanf(
file, "%d", &port);
fclose(
file);
printf ( "%d
n", port);
sockfd =
init_ser( port);
if ( sockfd == 0) {
printf( "Init server socket errorn");
fflush( stdout);
exit(1);
} //Socket init done
listen( sockfd, MAX_CLIENT);
cli_len = sizeof( cli_addr);
for ( i = 0; i
user_link[i] = 0;
username[i][0] = ' ';
}
userCount = 0;
FD_ZERO(
&sockset);
FD_SET(
sockfd, &sockset);
maxfd = max(
maxfd, sockfd+1);
for ( ; ;) {
select( maxfd, &sockset, NULL, NULL, NULL);
if ( FD_ISSET( sockfd, &sockset)
&& (userCount = user_free(
user_link)) >=0) {
new_sockfd = accept( sockfd, (struct
sockaddr*)&cli_addr,
&cli_len);
if ( new_sockfd < 0) {
user_link[userCount] = 0;
printf( "acc errorn");
} else {
user_link[userCount] = 1;
userfd[userCount] = new_sockfd;